获取给定类型的健康状况存储中的样本总数

时间:2018-06-21 03:50:35

标签: ios health-kit

是否有正确的方法(性能良好)来确定HealthKit存储中给定数据类型的样本总数?

我尝试过幼稚的方法:

let healthStore = HKHealthStore()
let sampleType = HKObjectType.quantityType(forIdentifier: .heartRate)
let query = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { _, samples, error in
    if let samples = samples {
        NSLog("Total count is: \(samples.count) for \(sampleType.identifier)")
    }
}
healthStore.execute(query)

这确实产生了我所期望的值,但是每当有大量数据(例如,用户使用Apple Watch时的心跳率),它的性能都会很差:它经常导致失控的内存消耗和崩溃。

我尝试的第二种方法是使用重复的HKSampleQuery迭代(以startDate降序排序,分别为limitpredicate来对样本进行计数。这是相当稳定的,但仍然需要一段时间(例如,花一分钟来汇总我数百万个心率样本):

func accumulate(sampleType: HKQuantityType, endDate: Date, previousCount: Int) {
    let earlierThanEndDate = HKQuery.predicateForSamples(withStart: nil, end: endDate, options: .strictStartDate)
    let byDateDescending = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
    let q = HKSampleQuery(sampleType: sampleType, predicate: earlierThanEndDate, limit: 10000, sortDescriptors: [byDateDescending]) { query, samples, error in
        guard let samples = samples else { return }
        guard !samples.isEmpty,
            let earliest = samples.last?.startDate else {
            return NSLog("The final count is: \(previousCount)")
        }
        self.accumulate(sampleType: sampleType, endDate: earliest, previousCount: previousCount + samples.count)
    }
    self.healthStore.execute(q)
}

accumulate(sampleType: mySampleType, endDate: Date(), previousCount: 0)

我没有比这更好的了。有没有更正确的方法来确定样本总数?

0 个答案:

没有答案