Source code for streaming Heart Rate

I'm completely new to HealthKit. I've watched the whats new in HealthKit session several times, but so far have been unable to figure out streaming heart rate data.


Does anyone have access to the source code they used in the session, or would be willing to share how they have figured out how to stream heart rate?


Thanks

Answered by bryan1anderson in 16580022

I figured it out on my own finally.


Here is source code: use wisely!


class InterfaceController: WKInterfaceController, HKWorkoutSessionDelegate  {
    let healthStore: HKHealthStore = HKHealthStore()
   
    @IBOutlet var label: WKInterfaceLabel!
   
    var workoutStartDate: NSDate?
    var workoutEndDate: NSDate?
   
    var queries: [HKQuery] = []
   
   
   
    var heartRateSampless: [HKQuantitySample] = []
    let countPerMinuteUnit = HKUnit(fromString: "count/min")
   
    let heartRateType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
   
    var currentHeartRateSample: HKQuantitySample?
   
   
   
    var currentHeartRateQuantity: HKQuantity!
   
   
   
   
    var activityType: HKWorkoutActivityType?
    var locationType: HKWorkoutSessionLocationType?
   
    var workoutSession: HKWorkoutSession?
   
   
   
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
       
        label.setText("hasn't been updated yet")
       
        activityType = HKWorkoutActivityType.MindAndBody
       
       
        locationType = HKWorkoutSessionLocationType.Indoor
        workoutSession = HKWorkoutSession(activityType: activityType!, locationType: locationType!)
       
        workoutSession!.delegate = self
       
        healthStore.startWorkoutSession(workoutSession!) { (update, error) -> Void in
           
        }
       
        let typesToShare = Set([HKObjectType.workoutType()])
        let typesToRead = Set([
            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
           
            ])
       
        self.healthStore.requestAuthorizationToShareTypes(typesToShare, readTypes: typesToRead) { (sucess, error) -> Void in
           
          
            print(sucess)
            print(error)
           
        }
       
       
        createStreamingHeartRateQuery(NSDate())
    }
   
   
    func getHeartRateSamples(samples: [HKSample]?) {
        guard let heartRateSamples = samples as? [HKQuantitySample] else { return }
       
        self.heartRateSampless = heartRateSamples
       
        for sample in heartRateSamples {
            print(sample.quantity)
            print(sample.startDate)
           
            let heartRate = sample.quantity
            let heartRateDouble = heartRate.doubleValueForUnit(countPerMinuteUnit)
           
            self.label.setText("\(heartRateDouble)")
           
        }
    }
   
   
    func createStreamingHeartRateQuery(workoutStartDate: NSDate) -> HKQuery {
       
       
        let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: .None)
        let type = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
        let heartRateQuery = HKAnchoredObjectQuery(type: type!, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in
           
        }
       
        heartRateQuery.updateHandler = {
            (query, samples, deletedObjects, anchor, error) -> Void in
           
            self.getHeartRateSamples(samples)
       
        }
       
        healthStore.executeQuery(heartRateQuery)
       
        let sampleHandler = { (samples: [HKQuantitySample]) -> Void in
      
        }
       
    
        return heartRateQuery
       
    }
   
   
    func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) {
       
       
       
    }
   
    func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) {
       
       
    }
   
}
 
Accepted Answer

I figured it out on my own finally.


Here is source code: use wisely!


class InterfaceController: WKInterfaceController, HKWorkoutSessionDelegate  {
    let healthStore: HKHealthStore = HKHealthStore()
   
    @IBOutlet var label: WKInterfaceLabel!
   
    var workoutStartDate: NSDate?
    var workoutEndDate: NSDate?
   
    var queries: [HKQuery] = []
   
   
   
    var heartRateSampless: [HKQuantitySample] = []
    let countPerMinuteUnit = HKUnit(fromString: "count/min")
   
    let heartRateType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
   
    var currentHeartRateSample: HKQuantitySample?
   
   
   
    var currentHeartRateQuantity: HKQuantity!
   
   
   
   
    var activityType: HKWorkoutActivityType?
    var locationType: HKWorkoutSessionLocationType?
   
    var workoutSession: HKWorkoutSession?
   
   
   
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
       
        label.setText("hasn't been updated yet")
       
        activityType = HKWorkoutActivityType.MindAndBody
       
       
        locationType = HKWorkoutSessionLocationType.Indoor
        workoutSession = HKWorkoutSession(activityType: activityType!, locationType: locationType!)
       
        workoutSession!.delegate = self
       
        healthStore.startWorkoutSession(workoutSession!) { (update, error) -> Void in
           
        }
       
        let typesToShare = Set([HKObjectType.workoutType()])
        let typesToRead = Set([
            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
           
            ])
       
        self.healthStore.requestAuthorizationToShareTypes(typesToShare, readTypes: typesToRead) { (sucess, error) -> Void in
           
          
            print(sucess)
            print(error)
           
        }
       
       
        createStreamingHeartRateQuery(NSDate())
    }
   
   
    func getHeartRateSamples(samples: [HKSample]?) {
        guard let heartRateSamples = samples as? [HKQuantitySample] else { return }
       
        self.heartRateSampless = heartRateSamples
       
        for sample in heartRateSamples {
            print(sample.quantity)
            print(sample.startDate)
           
            let heartRate = sample.quantity
            let heartRateDouble = heartRate.doubleValueForUnit(countPerMinuteUnit)
           
            self.label.setText("\(heartRateDouble)")
           
        }
    }
   
   
    func createStreamingHeartRateQuery(workoutStartDate: NSDate) -> HKQuery {
       
       
        let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: .None)
        let type = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
        let heartRateQuery = HKAnchoredObjectQuery(type: type!, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in
           
        }
       
        heartRateQuery.updateHandler = {
            (query, samples, deletedObjects, anchor, error) -> Void in
           
            self.getHeartRateSamples(samples)
       
        }
       
        healthStore.executeQuery(heartRateQuery)
       
        let sampleHandler = { (samples: [HKQuantitySample]) -> Void in
      
        }
       
    
        return heartRateQuery
       
    }
   
   
    func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) {
       
       
       
    }
   
    func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) {
       
       
    }
   
}
 

Search github "watchOS-2-heartrate"

Does the watch simulator "simulates" heart rate.or I need to use the device for this code?

Had the same question here: https://forums.developer.apple.com/thread/7339.


The simulator won't simulate workout data so you need to test on the device. The best we can do for now is to request this feature be added to the developer tools https://bugreport.apple.com.

Has anyone received heart rate updates on the second with this? I noticed that with the updateHandler, or polling once a second, the value only ever changes every 5 seconds. I have tried different activities (Running/Walking/Other), and all produce the same 5 second update.

       let heartRateQuery = HKAnchoredObjectQuery(type: type!, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in
                      
        }


I get an error on this line that says

Cannot invoke initializer for type 'HKAnchoredObjectQuery' with an argument list of type '(type: ...'

! Expected an argument list of type '()'


I have no idea how to debug this...

Source code for streaming Heart Rate
 
 
Q