Skip to content

Instantly share code, notes, and snippets.

@eriadam
Created March 1, 2018 21:04
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save eriadam/5c6565c32c5af77948673a69a6e8f3a4 to your computer and use it in GitHub Desktop.
Save eriadam/5c6565c32c5af77948673a69a6e8f3a4 to your computer and use it in GitHub Desktop.
public func subscribeToHeartBeatChanges() {
// Creating the sample for the heart rate
guard let sampleType: HKSampleType =
HKObjectType.quantityType(forIdentifier: .heartRate) else {
return
}
/// Creating an observer, so updates are received whenever HealthKit’s
// heart rate data changes.
self.heartRateQuery = HKObserverQuery.init(
sampleType: sampleType,
predicate: nil) { [weak self] _, _, error in
guard error == nil else {
log.warn(error!)
return
}
/// When the completion is called, an other query is executed
/// to fetch the latest heart rate
self.fetchLatestHeartRateSample(completion: { sample in
guard let sample = sample else {
return
}
/// The completion in called on a background thread, but we
/// need to update the UI on the main.
DispatchQueue.main.async {
/// Converting the heart rate to bpm
let heartRateUnit = HKUnit(from: "count/min")
let heartRate = sample
.quantity
.doubleValue(for: heartRateUnit)
/// Updating the UI with the retrieved value
self?.heartRateLabel.setText("\(Int(heartRate))")
}
})
}
}
public func fetchLatestHeartRateSample(
completion: @escaping (_ sample: HKQuantitySample?) -> Void) {
/// Create sample type for the heart rate
guard let sampleType = HKObjectType
.quantityType(forIdentifier: .heartRate) else {
completion(nil)
return
}
/// Predicate for specifiying start and end dates for the query
let predicate = HKQuery
.predicateForSamples(
withStart: Date.distantPast,
end: Date(),
options: .strictEndDate)
/// Set sorting by date.
let sortDescriptor = NSSortDescriptor(
key: HKSampleSortIdentifierStartDate,
ascending: false)
/// Create the query
let query = HKSampleQuery(
sampleType: sampleType,
predicate: predicate,
limit: Int(HKObjectQueryNoLimit),
sortDescriptors: [sortDescriptor]) { (_, results, error) in
guard error == nil else {
print("Error: \(error!.localizedDescription)")
return
}
completion(results?[0] as? HKQuantitySample)
}
self.healthStore.execute(query)
}
@NicoleOlsonCIS
Copy link

Could you please provide some additional context? Where does this code go, and what includes are required? Thanks!

@eriadam
Copy link
Author

eriadam commented Nov 18, 2020

Hello, this is an example that belongs to the medium article in here: https://medium.com/ios-os-x-development/apple-watch-app-displaying-the-heart-rate-b3555f3e148d

@nabeelawan00
Copy link

Please upload complete example with all variable defined inti

@eriadam
Copy link
Author

eriadam commented Apr 2, 2021

Hey @nabeelawan00, this is not an open source project. I am happy to support you, just reach out to contact@blackmirror.media.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment