In watchOS, is there a way to detect if a body is present to determine whether or not to show a heart rate?
I am finding that when I take the watch off, the heart rate sensor keeps returning values. I want to show "-" when the watch is taken off.
Below is the function I am using to get the heart rate.
Thanks.
private func heartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
// We want data points from our current device
let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
// A query that returns changes to the HealthKit store, including a snapshot of new changes and continuous monitoring as a long-running query.
let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
query, samples, deletedObjects, queryAnchor, error in
// A sample that represents a quantity, including the value and the units.
guard let samples = samples as? [HKQuantitySample] else {
return
}
self.process(samples, type: quantityTypeIdentifier)
}
// Provides with both the ability to receive a snapshot of data, and then on subsequent calls, a snapshot of what has changed.
let query = HKAnchoredObjectQuery(type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!, predicate: devicePredicate, anchor: nil, limit: HKObjectQueryNoLimit, resultsHandler: updateHandler)
query.updateHandler = updateHandler
// query execution
healthStore.execute(query)
}
private func processHeartRate(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
// Variable initialization
var lastHeartRate = 0.0
// Get the first sample value
guard let sample = samples.first else{
print("No samples!")
return
}
// Get current heart rate
if type == .heartRate {
lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
self.value = Int(lastHeartRate)
hrLabel.setText(String(value))
print("The lastHeartRate is \(lastHeartRate)")
}
}