Watch os 2.0 beta: access heart beat rate

Sr.Richie picture Sr.Richie · Jun 11, 2015 · Viewed 11.9k times · Source

With Watch OS 2.0 developers are supposed to be allowed to access heart beat sensors.... I would love to play a bit with it and build a simple prototype for an idea I have, but I can't find anywhere info or documentation about this feature.

Can anyone point me on how to approach this task? Any link or info would be appreciated

Answer

lehn0058 picture lehn0058 · Aug 6, 2015

Apple isn't technically giving developers access to the heart rate sensors in watchOS 2.0. What they are doing is providing direct access to heart rate data recorded by the sensor in HealthKit. To do this and get data in near-real time, there are two main things you need to do. First, you need to tell the watch that you are starting a workout (lets say you are running):

// Create a new workout session
self.workoutSession = HKWorkoutSession(activityType: .Running, locationType: .Indoor)
self.workoutSession!.delegate = self;

// Start the workout session
self.healthStore.startWorkoutSession(self.workoutSession!)

Then, you can start a streaming query from HKHealthKit to give you updates as HealthKit receives them:

// This is the type you want updates on. It can be any health kit type, including heart rate.
let distanceType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)

// Match samples with a start date after the workout start
let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: .None)

let distanceQuery = HKAnchoredObjectQuery(type: distanceType!, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in
    // Handle when the query first returns results
    // TODO: do whatever you want with samples (note you are not on the main thread)
}

// This is called each time a new value is entered into HealthKit (samples may be batched together for efficiency)
distanceQuery.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
    // Handle update notifications after the query has initially run
    // TODO: do whatever you want with samples (note you are not on the main thread)
}

// Start the query
self.healthStore.executeQuery(distanceQuery)

This is all described in full detail in the demo at the end of the video What's New in HealthKit - WWDC 2015