我想从iPhone应用程序和Apple Watch应用程序向HealthKit添加样本。有一个条件:如果在过去10分钟内已经添加了另一个样本,我想替换它(或删除+添加)。
这就是我的所作所为。
func addOrUpdateSample(beans:Float) {
let dateThreshold = NSDate().dateByAddingTimeInterval(-10 * 60)
let predicate:NSPredicate = NSPredicate(format:"startDate >= %@",dateThreshold)
let sortDescriptor:NSSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
let query:HKSampleQuery = HKSampleQuery(sampleType: caffeineType!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors:[sortDescriptor]) { (query, results, error) in
// Remove all samples that match the predicate…
if results != nil {
for result in results! {
self.healthStore?.deleteObject(result, withCompletion: { (success, error) in })
}
}
// …before adding the new sample
let sample = self.createSample(beans) // Helper returning a HKQuantitySample object
self.healthStore?.saveObject(sample, withCompletion: { (success, error) in })
}
healthStore?.executeQuery(query)
}
在iOS上,这按预期工作,在添加新对象之前删除所有现有对象。从Apple Watch App启动时,是否添加了样本,但没有样本被删除?
是否正在删除watchOS上不支持的样本,或者我是否遗漏了某些内容?