简体   繁体   中英

Query HealthKit for HKCategoryTypeIdentifierSleepAnalysis

I have built a method that imports a sleep sample but I can't get it to return the proper value for hours asleep.

The method to query for sleep data looks like this:

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)
}

The date is formatted like this:

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)
    }
}

I'm calling data from November 4-5, which contains this data:

However, the categorySample.value returns 1 instead of 3 .

The value you are accessing is the category sample value, an HKCategoryType , and not the number of hours of sleep.

The definition for HKCategoryTypeIdentifierSleepAnalysis

typedef enum : NSInteger {
   HKCategoryValueSleepAnalysisInBed,
   HKCategoryValueSleepAnalysisAsleep,
} HKCategoryValueSleepAnalysis;

defines two possible values, 0 or 1 where the value of 1 matches HKCategoryValueSleepAnalysisAsleep .

Getting the hours asleep requires setting up a HKSampleQuery .

The code looks something like this:

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)
}

I summarized this from http://benoitpasquier.fr/sleep-healthkit/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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