如何从 HealthKit 中检索今天的正念记录?

How to retrieve today's mindful minutes from HealthKit?

我试图从 HealthKit 获取今天的正念分钟数,但我总是得到 44280 而不是健康应用程序中的 3,我编写了这个函数:

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 {
                    print(" HealthKit returned error while trying to query today's mindful sessions. The error was: \(error?.localizedDescription)")
                }
                var totalTime = TimeInterval()
                if let results = results {
                    for result in results {
                        totalTime = result.endDate.timeIntervalSince(startDate)
                        completion(totalTime)
                    }
                } else {
                    completion(0)
                }
            }
            healthStore.execute(query)

        }

}

我该怎么办?

当你计算时间时,你使用这个代码:

if let results = results {
    for result in results {
        totalTime = result.endDate.timeIntervalSince(startDate)
        completion(totalTime)
    }
} else {
    completion(0)
}

然而,它并没有按照你的想法去做。它有两个主要问题:

  1. 您获取的不是会话的时长,而是从会话结束到一天开始的时间。要解决此问题,请使用 totalTime = result.endDate.timeIntervalSince(result.startDate)
  2. 我看到的另一个问题是您调用 completion 每个会话的长度,而不是总时间.这可能是您想要的,但如果不是,请将查询的内部更改为:
if error != nil {
    print(" HealthKit returned error while trying to query today's mindful sessions. The error was: \(error?.localizedDescription)")
}
if let results = results {
    var totalTime = TimeInterval()
    for result in results {
        totalTime += result.endDate.timeIntervalSince(result.startDate)
    }
    completion(totalTime)
} else {
    completion(0)
}

这会在调用完成处理程序之前对所有会话求和。

希望对您有所帮助!