-
-
Save eriadam/3c3d5077edb11e91cbf276b76b843c34 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment