使用HealthKit获取睡眠时间

时间:2017-12-04 11:17:06

标签: ios swift health-kit

我想通过HealthKit获取特定日期的睡眠时间。 我有谷歌,但没有找到任何具体的解决方案。我也尝试使用下面的代码,但它不能很好地工作。

func getSleepHours()  {
        if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {

            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy/MM/dd HH:mm"
            let startDate = formatter.date(from: "2017/12/02 22:00")

            let endDate = formatter.date(from: "2017/12/03 07:31")

//            let startDate = Date().yesterday
//            let endDate = Date()

            //let starTDate = Date)


            let predciate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictEndDate)

         //   let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, startDate: endDate, options: .None)
            let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
            let query = HKSampleQuery(sampleType: sleepType, predicate: predciate, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
                if let result = tmpResult {
                    for item in result {
                        if let sample = item as? HKCategorySample {
                            let value = (sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue) ? "InBed" : "Asleep"
                            print("sleep: \(sample.startDate) \(sample.endDate) - source: \(sample.source.name) - value: \(value)")
                         //   let seconds = endDate.timeIntervalSinceDate(sample.startDate)
                            let seconds = sample.startDate.timeIntervalSince(sample.endDate)
                            let minutes = seconds/60
                            let hours = minutes/60
                            print(seconds)
                            print(minutes)
                            print(hours)
                        }
                    }
                }else{
                    print(error?.localizedDescription)
                }
            }

            healthStore.execute(query)
        }
    }

0 个答案:

没有答案