阅读正念纪要

Reading Mindful Minutes

美好的一天,

我的健身应用程序即将推出,我可以查询 HealthKit 以获取其他数据,但我很难获得正念时间。这是我拥有的:

//MARK: - Read Mindful Minutes
func readMindfulMinutes(date: Date) {

    guard let mindfulMinutes = HKSampleType.categoryType(forIdentifier: .mindfulSession) else {
        print("Sample type not available")
        return
    }

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

    let mindfulMinutesQuery = HKSampleQuery(sampleType: mindfulMinutes,
                                            predicate: predicate,
                                            limit: HKObjectQueryNoLimit,
                                            sortDescriptors: nil) {
                                                (query, samples, error) in

                                    guard
                                        error == nil,
                                    let quantitySamples = samples as? [HKQuantitySample] else {
                                            print("Something went wrong: \(String(describing: error))")
                                            return
                                    }

                                        let total = quantitySamples.reduce(0.0) { [=10=] + .quantity.doubleValue(for: HKUnit.minute()) }
                                    DispatchQueue.main.async {
                                        self.userMindfulMinutes = total
                                        print("userMindfulMinutes = \(self.userMindfulMinutes)")
                                    }

    }
    HKHealthStore().execute(mindfulMinutesQuery)
}

}

我总是从 print 语句中传递 "Something went wrong: nil"。非常感谢任何帮助。

您不能将类别样本强制转换为数量样本。那就是失败的原因。 您必须计算每个会话记录的分钟数。 尝试;

  let totalMeditationTime = samples?.map(calculateMinutes).reduce(0, { [=10=] +  }) ?? 0

并将 calculateMinutes 定义为;

   func calculateMinutes(sample: HKSample) -> TimeInterval
   {
       return sample.endDate.timeIntervalSince(sample.startDate)
   }