[英]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.
实际上,标签的文本与我在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.
我已经将这种模式用于其他HealthKit数据,例如每日步数,但我不知道为什么这没有效果。
EDIT: NEVERMIND, it was a really stupid error, I should've put completion(totalTime)
after the for-in loop. 编辑:没关系,这是一个非常愚蠢的错误,我应该在
completion(totalTime)
循环之后放置completion(totalTime)
。 OOPS OOPS
NEVERMIND, it was a really stupid error, I should've put completion(totalTime) after the for-in loop. 没关系,这是一个非常愚蠢的错误,我应该在完成循环之后放置completion(totalTime)。 OOPS
OOPS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.