2015-11-06 66 views
3

我已經建立了一個方法,導入睡眠樣本,但我不能讓它返回適當的值睡了幾個小時。查詢HealthKit HKCategoryTypeIdentifierSleepAnalysis

來查詢睡眠數據的方法是這樣的:

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

回答

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/