I'm making a workout app for Apple Watch.
I start HKWorkoutSession, then associate it with HKLiveWorkoutBuilder and begin listening for heart rate and calorie changes.
I have 2 options on how to get a heart rate or calories:
2. Executing HKAnchoredObjectQuery:
Which of the options is preferable?
Are there any benefits of using one over another?
Big thanks for all your responses!
I start HKWorkoutSession, then associate it with HKLiveWorkoutBuilder and begin listening for heart rate and calorie changes.
I have 2 options on how to get a heart rate or calories:
Using HKLiveWorkoutBuilder statistics:
Code Block let heartRate = HKQuantityType.quantityType(forIdentifier: .heartRate), let statistics = builder.statistics(for: heartRate){ let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let value = statistics.mostRecentQuantity()?.doubleValue(for: heartRateUnit)
2. Executing HKAnchoredObjectQuery:
Code Block let heartRateSample = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> () = { query, newResult, deleted, newAnchor, error in if let samples = newResult as? [HKQuantitySample] { guard samples.count > 0 else { return } for sample in samples { let value = sample.quantity.doubleValue(for: heartRateUnit) value = Int(value) } } } heartRateQuery = HKAnchoredObjectQuery(type: heartRateSample!, predicate: nil, anchor: nil, limit: Int(HKObjectQueryNoLimit), resultsHandler: updateHandler) heartRateQuery!.updateHandler = updateHandler store?.execute(heartRateQuery!)
Which of the options is preferable?
Are there any benefits of using one over another?
Big thanks for all your responses!