简体   繁体   English

如何仅查询 HealthKit 以获取给定日期的总“在床上”时间?

[英]How to only query HealthKit for Total "In Bed" time for a given day?

There isn't a whole of sample code on the internet for querying for sleep data.互联网上没有用于查询睡眠数据的完整示例代码。 The below code will return all sleep samples from a given day which if you look at the Apple Health App include "Asleep" samples from the Apple Watch which are sleep intervals, but there is also an "In Bed" sample from the iPhone which contains the total range from getting in bed to getting out of bed.下面的代码将返回给定日期的所有睡眠样本,如果您查看 Apple Health App,其中包括来自 Apple Watch 的“睡眠”样本,它们是睡眠间隔,但也有来自 iPhone 的“床上”样本,其中包含从上床到下床的总范围。 How can I query HealthKit for only this In Bed sample?如何仅查询 HealthKit 以获取此 In Bed 样本?

func sleepTime() {
        let healthStore = HKHealthStore()
        // startDate and endDate are NSDate objects
        // first, we define the object type we want
        if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {
            // You may want to use a predicate to filter the data... startDate and endDate are NSDate objects corresponding to the time range that you want to retrieve
            //let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,endDate: endDate ,options: .None)
            // Get the recent data first
            let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
            // the block completion to execute
            let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 100000, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
                if error != nil {
                    // Handle the error in your app gracefully
                    return
                }
                if let result = tmpResult {
                   for item in result {
                        if let sample = item as? HKCategorySample {
                               let startDate = sample.startDate
                               let endDate = sample.endDate
                               print()
                             let sleepTimeForOneDay = sample.endDate.timeIntervalSince(sample.startDate)
                        }
                    }
                }
          }
    }

HKCategorySample contains the value of type Int which is the enumeration value for the sample. HKCategorySample 包含Int类型的,它是样本的枚举值。 It has three values:它具有三个值:

0 -> inBed 0 -> 在床上

1 -> asleep 1 -> 睡着了

2 -> awake 2 -> 醒着

So, the proposed change if you only want inBed data is:因此,如果您只需要 inBed 数据,建议的更改是:

if let result = tmpResult {
                for item in result {
                    if let sample = item as? HKCategorySample {
                        if sample.value == 0 {
                            let startDate = sample.startDate
                            let endDate = sample.endDate
                            print()
                            let sleepTimeForOneDay = sample.endDate.timeIntervalSince(sample.startDate)
                            
                        }
                    }
                }
            }

Better way is to go with switch case.更好的方法是 go 与开关盒。

if let result = tmpResult {
                for item in result {
                    if let sample = item as? HKCategorySample {
                        switch sample.value {
                        case 0:
                            // inBed, write logic here
                            print("inBed")
                        case 1:
                            // asleep, write logic here
                            print("asleep")
                        default:
                            // awake, write logic here
                            print("awake")
                        }
                    }
                }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM