Reputation: 215
I'm trying to calculate how many mindful minutes the user had during the day, so I tried to do this:
func getDailyMindfulnessTime(completion: @escaping (TimeInterval) -> Void) {
let sampleType = HKSampleType.categoryType(forIdentifier: .mindfulSession)!
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let startDate = Calendar.current.startOfDay(for: Date())
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
let query = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (_, results, error) in
if error != nil {
fatalError("*** HealthKit returned error while trying to query today's mindful sessions. The error was: \(String(describing: error))")
}
var totalTime = TimeInterval()
if let results = results {
for result in results {
totalTime += result.endDate.timeIntervalSince(startDate)
}
} else {
completion(0)
}
}
healthStore.execute(query)
}
then:
healthStore.getDailyMindfulnessTime { (result) in
self.meditationTodayMinutesLabel.text = "\(result) minutes today"
}
But this doesn't seem to work. In fact, the label's text doesn't change from what I set it to in Interface Builder. I've used this kind of pattern for other HealthKit data like daily step count, but I don't know why this has no effect.
EDIT: NEVERMIND, it was a really stupid error, I should've put completion(totalTime)
after the for-in loop. OOPS
Upvotes: 0
Views: 361
Reputation: 215
NEVERMIND, it was a really stupid error, I should've put completion(totalTime) after the for-in loop. OOPS
Upvotes: 1