Ios 如何使用HealthKit睡眠查询区分来源
我目前正在使用以下代码查询用户在过去24小时内睡眠的小时数:Ios 如何使用HealthKit睡眠查询区分来源,ios,swift,healthkit,Ios,Swift,Healthkit,我目前正在使用以下代码查询用户在过去24小时内睡眠的小时数: func getHealthKitSleep() { let healthStore = HKHealthStore() let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) // Get all samples from the last 24 ho
func getHealthKitSleep() {
let healthStore = HKHealthStore()
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// Get all samples from the last 24 hours
let endDate = Date()
let startDate = endDate.addingTimeInterval(-1.0 * 60.0 * 60.0 * 24.0)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
// Sleep query
let sleepQuery = HKSampleQuery(
sampleType: HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!,
predicate: predicate,
limit: 0,
sortDescriptors: [sortDescriptor]){ (query, results, error) -> Void in
if error != nil {return}
// Sum the sleep time
var minutesSleepAggr = 0.0
if let result = results {
for item in result {
if let sample = item as? HKCategorySample {
if sample.value == HKCategoryValueSleepAnalysis.asleep.rawValue && sample.startDate >= startDate {
let sleepTime = sample.endDate.timeIntervalSince(sample.startDate)
let minutesInAnHour = 60.0
let minutesBetweenDates = sleepTime / minutesInAnHour
minutesSleepAggr += minutesBetweenDates
}
}
}
self.sleep = Double(String(format: "%.1f", minutesSleepAggr / 60))!
print("HOURS: \(String(describing: self.sleep))")
}
}
// Execute our query
healthStore.execute(sleepQuery)
}
如果用户只有一个睡眠应用程序作为数据源,这将非常有效。问题是,例如,如果用户使用2个睡眠应用程序作为源,数据将加倍。如何区分来源?如果能够区分数据源,我希望只从一个数据源获取数据,或者取数据源的平均值。当您在样本上循环时,您可以访问每个数据源的信息。我只接受一个源,所以我只保留源名称的一个变量,如果当前示例具有不同的源名称,我将继续循环,而不处理来自该示例的数据,但是如果需要,可以用其他方式组合数据 以下是如何访问源信息:
if let sample = item as? HKCategorySample {
let name = sample.sourceRevision.source.name
let id = sample.sourceRevision.source.bundleIdentifier
}
关于HKSourceRevision
对象有更多信息