我正在尝试计算用户白天有多少分钟的注意力,所以我尝试这样做:
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)
}
然后:
healthStore.getDailyMindfulnessTime { (result) in
self.meditationTodayMinutesLabel.text = "\(result) minutes today"
}
但这似乎不起作用。实际上,标签的文本与我在Interface Builder中设置的一样。我已经将这种模式用于其他HealthKit数据,例如每日步数,但我不知道为什么这没有效果。
编辑:没关系,这是一个非常愚蠢的错误,我应该在for-in循环之后放置completion(totalTime)
。哎呀
答案 0 :(得分:0)
没关系,这是一个非常愚蠢的错误,我应该在完成循环之后放置completion(totalTime)。哎呀