Using Apple's sample code from SpeedySloth, I am getting heart rate samples on the simulator but not getting any samples on my Series 0 Apple Watch running WatchOS 4.1. Is this a bug? Anyone else having this issue?
code:
func startHeartRateQuery(from startDate: Date, updateHandler: @escaping ([HKQuantitySample]) -> Void) {
let typeIdentifier = HKQuantityTypeIdentifier.heartRate
startQuery(ofType: typeIdentifier, from: startDate) { _, samples, _, _, error in
guard let quantitySamples = samples as? [HKQuantitySample] else {
print("Heart rate query failed with error: \(String(describing: error))")
return
}
print("heartRate samples = \(quantitySamples)")
updateHandler(quantitySamples)
}
}
//Generic helper function
private func startQuery(ofType type: HKQuantityTypeIdentifier, from startDate: Date, handler: @escaping
(HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void) {
let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: nil, options: .strictStartDate)
let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate, devicePredicate])
let quantityType = HKObjectType.quantityType(forIdentifier: type)!
let query = HKAnchoredObjectQuery(type: quantityType, predicate: queryPredicate, anchor: nil,
limit: HKObjectQueryNoLimit, resultsHandler: handler)
query.updateHandler = handler
healthStore.execute(query)
activeDataQueries.append(query)
}
I ended up upgrading my watch from a series 0 to a series 3, and I no longer have any problem getting heart rates on WatchOS 4.1. The problem may have been hardware related. Posting an update to show my code above is good for pulling heart rate data.