查询HealthCit for HKCategoryTypeIdentifierSleepAnalysis

时间:2015-11-06 00:09:51

标签: ios swift nsdate health-kit

我已经构建了一个导入睡眠样本的方法,但是我无法让它在几小时后返回正确的值。

查询睡眠数据的方法如下所示:

func updateHealthCategories() {

    let categoryType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)

    let start = NSDate(dateString:"2015-11-04")
    let end = NSDate(dateString:"2015-11-05")

    let categorySample = HKCategorySample(type: categoryType!,
        value: HKCategoryValueSleepAnalysis.Asleep.rawValue,
        startDate: start,
        endDate: end)

    self.hoursSleep = Double(categorySample.value)

    print(categorySample.value)
}

日期的格式如下:

extension NSDate
{
    convenience
    init(dateString:String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        let d = dateStringFormatter.dateFromString(dateString)!
        self.init(timeInterval:0, sinceDate:d)
    }
}

我从11月4日到5月调用数据,其中包含以下数据:

但是,categorySample.value会返回1而不是3

1 个答案:

答案 0 :(得分:6)

您要访问的值是类别样本值,HKCategoryType,而不是睡眠小时数。

HKCategoryTypeIdentifierSleepAnalysis

的定义
typedef enum : NSInteger {
   HKCategoryValueSleepAnalysisInBed,
   HKCategoryValueSleepAnalysisAsleep,
} HKCategoryValueSleepAnalysis;

定义了两个可能的值,0或1,其中值1匹配HKCategoryValueSleepAnalysisAsleep

让小时入睡需要设置HKSampleQuery

代码看起来像这样:

if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {

    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
    let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, 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 = sample.endDate.timeIntervalSinceDate(sample.startDate)
                    let minutes = seconds/60
                    let hours = minutes/60
                }
            }
        }
    }

    healthStore.executeQuery(query)
}

我从http://benoitpasquier.fr/sleep-healthkit/汇总了这一点。