Reputation: 81
I'm trying to return the last 7 days samples of heartbeat recorded. I think i'm on the good way but i'm still not quite sure about my query part. Here's what I've done so far. The only think that is getting printed is
95 count/min 90EBAB07-9CAB-445E-A967-4BD5E8AADAA4 "User’s Apple Watch" (5.1.3), "Watch3,2" (5.1.3)"Apple Watch" metadata: {
HKMetadataKeyHeartRateMotionContext = 0;
} (2019-02-22 21:51:31 -0400 - 2019-02-22 21:51:31 -0400)
here's my query:
func getTodaysHeartRate(completion: (@escaping (HKQuantitySample) -> Void)) {
let sortDescriptor = NSSortDescriptor(
key: HKSampleSortIdentifierEndDate,
ascending: false)
let heartRateType = HKSampleType.quantityType(forIdentifier: .heartRate)!
let endDate = Date()
let startDate = endDate.addingTimeInterval(-1.0 * 60 * 60 * 24)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
let query = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor])
{ (query, result, error) -> Void in
DispatchQueue.main.async {
guard let result = result,
let resultCount = result.first as? HKQuantitySample else {
print("Failed to fetch heart rate")
return
}
completion(resultCount)
}
}
healthStore.execute(query)
}
@IBOutlet weak var heartRate: UILabel!
@IBAction func getHeartRate(_ sender: Any) {
getTodaysHeartRate { (result) in
print("\(result)")
DispatchQueue.main.async {
self.heartRate.text = "\(result)"
}
}
Upvotes: 2
Views: 977
Reputation: 113
This should return you the last 7 days. Hope it help!
let startDate = Date() - 7 * 24 * 60 * 60
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
Upvotes: 1