@H_502_1@我已经构建了一个导入睡眠样本的方法,但我无法让它在几小时内返回正确的值.
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) }