WatchOS2-NewAPI-HealthKit-HeartReateExample icon indicating copy to clipboard operation
WatchOS2-NewAPI-HealthKit-HeartReateExample copied to clipboard

WatchOS 2 Experiments - New API Components - Streaming HeartRate with HealthKit Framework.

WatchOS2 - New API - HealthKit - Heartrate Example

WatchOS 2 Experiments - New API Components - Heartrate with HealthKit Framework.

Example

Requirements

  • = XCode 8.

  • = Swift 3.

  • = WatchOS2.

Tested on WatchOS2, iOS 9.1 Simulators.

Usage

To run the example project, download or clone the repo.

Important

this is the Xcode 8 / Swift 3 updated project.

Caution

  • HealthKit required in linked Framework and libraries.
  • You must allow app to access your streaming heartrate from iPhone
  • Change the 'Team' setting on [General] for each target.

Example Code!

Configure :

  • Customize your Interface Controller (Storyboard)
  • import HealthKit to your Interface Controller class
// create store object
let healthStore = HKHealthStore()

// create HKWorkoutSession with ActivityType (Cycling, Walking ...)
let workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Indoor)
let heartRateUnit = HKUnit(fromString: "count/min")
var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))

  • in interface context object method
workoutSession.delegate = self
  • in willActivate() method
/// Indicates whether HealthKit is available on this device
guard HKHealthStore.isHealthDataAvailable() == true else {
    infoLabel.setText("not available")
    return
}
/// To create samples that store a numerical value
guard let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else {
    //..
    return
}
/// Request permission to save and read the specified data types
let dataTypes = Set(arrayLiteral: quantityType)
healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypes) { (success, error) -> Void in
    if success == false {
        //..
    }
}
  • HKWorkoutSessionDelegate required
extension WKInterfaceController : HKWorkoutSessionDelegate {

func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) {
    dispatch_async(dispatch_get_main_queue()) {
        switch toState {
            case .Running:
                self.workoutDidStart(date)
            case .Ended:
                self.workoutDidEnd(date)
            default:
                print("unexpected \(toState)")
        }
    }
}

func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) {
    print("workOutSession Error : \(error.localizedDescription)")
    }
}

Build and Run on simulator or physical watch! Get datas in Health App!