Skip to content

Instantly share code, notes, and snippets.

@eriadam
Created March 1, 2018 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eriadam/3c3d5077edb11e91cbf276b76b843c34 to your computer and use it in GitHub Desktop.
Save eriadam/3c3d5077edb11e91cbf276b76b843c34 to your computer and use it in GitHub Desktop.
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