使用Swift计算HealthKit的总睡眠时间

使用Swift计算HealthKit的总睡眠时间,swift,healthkit,Swift,Healthkit,还有一个问题!我正在尝试从健康应用程序计算睡眠总时间。我可以通过以下方式获得信息: func readSleepAnalysis(date: Date) { if let mindfulType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) { let startDate = convertStartDate(StartDate: date)

还有一个问题!我正在尝试从健康应用程序计算睡眠总时间。我可以通过以下方式获得信息:

func readSleepAnalysis(date: Date) {

    if let mindfulType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {

        let startDate = convertStartDate(StartDate: date)
        let endDate = convertEndDate(EndDate: date)
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)

        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)

        let query = HKSampleQuery(sampleType: mindfulType, predicate: predicate, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in

            if error != nil {
                    print("Something went wrong getting sleep analysis: \(String(describing: error))")
                return
            }
            if let result = tmpResult {

                for item in result {
                    if let sample = item as? HKCategorySample {
                        let value = (sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue) ? "InBed" : "Asleep"
                            print("Healthkit sleep: \(sample.startDate) \(sample.endDate) value: \(value)")
                    }
                }
            }
        }
        healthKit.execute(query)
    }
}
然而,我得到:

Healthkit睡眠:2020-04-13 01:27:55+0000 2020-04-13 11:49:51+0000值:内置

Healthkit睡眠:2020-04-13 02:46:41+0000 2020-04-13 11:49:51+0000值:睡眠

Healthkit睡眠:2020-04-12 07:48:06+0000 2020-04-12 12:32:59+0000值:睡眠

Healthkit睡眠:2020-04-1204:18:33+0000 2020-04-1207:17:29+0000值:睡眠

我想得到的只是睡眠时间的总和,以小时为单位:分钟


一如既往,我们非常感谢您的任何建议或意见。

您好,您找到解决方案了吗?您好,您找到解决方案了吗?