ios – 为HKCategoryTypeIdentifierSleepAnalysis查询HealthKit

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

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

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.

解决方法

您要访问的值是类别样本值,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/总结了这一点.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...