简体   繁体   中英

How to get daily mindful time from HealthKit?

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

NEVERMIND, it was a really stupid error, I should've put completion(totalTime) after the for-in loop. OOPS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM