所以在我读完答案之后,我现在明白我需要使用查询来检索Health中的数据,并尝试使用代码:
let deletedType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCaffeine)
let predicate = HKQuery.predicateForSamples(withStart: dataDate as Date, end: dataDate as Date, options: .strictStartDate)
let findQuery = HKSampleQuery(sampleType: deletedType!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) {
query, results, error in
if results != nil {
print("\nHere we got not nil on results!\n")
for result in (results as? [HKQuantitySample])! {
let quantity = result.quantity.doubleValue(for: HKUnit.gramUnit(with: .milli))
print(quantity)
}
} else {
print("results are nil")
return
}
}
healthKitStore.execute(findQuery)
我没有在resultHander块中做很多事情,我首先要查看我找到的数据,当我注意数量时,我注意到了,但我确实得到了"我们没有nl on resluts"这意味着结果不是零。我对iOS开发很新鲜,我检查了HKHealthSample的文档,但是找不到我的HKSampleQuery的哪个部分错了!
我有一个应用程序,通过HealthKit将咖啡因数据写入健康状况 这是保存功能
func saveCaffeine(_ caffeineRecorded: Double, dataDate: Date) {
// Set the quantity type to the running/walking distance.
let caffeineType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCaffeine)
// Set the unit of measurement to miles.
let caffeineQuantity = HKQuantity(unit: HKUnit.gramUnit(with: .milli), doubleValue: caffeineRecorded)
// Set the official Quantity Sample.
let caffeine = HKQuantitySample(type: caffeineType!, quantity: caffeineQuantity, start: dataDate, end: dataDate)
print("\n to be added: \(caffeine) \n")
// Save the distance quantity sample to the HealthKit Store.
healthKitStore.save(caffeine, withCompletion: { (success, error) -> Void in
if( error != nil ) {
print(error!)
} else {
print("The Caffeine has been recorded! Better go check!")
}
})
}
然后它成功保存,之后我从表视图中删除并转到另一个删除函数时检索数据:
func deleteCaffeine(_ caffeineRecorded: Double, dataDate: Date){
let caffeineType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCaffeine)
let caffeineQuantity = HKQuantity(unit: HKUnit.gramUnit(with: .milli), doubleValue: caffeineRecorded)
let coffeeBeenDeleted = HKQuantitySample(type: caffeineType!, quantity: caffeineQuantity, start: dataDate, end: dataDate)
print("\n to be deleted: \(coffeeBeenDeleted) \n")
healthKitStore.delete(coffeeBeenDeleted, withCompletion: {(success, error) -> Void in
if (error != nil) {
print(error!)
} else {
print("This caffeine data just been deleted!")
}
})
}
然后我收到错误:Error Domain = com.apple.healthkit Code = 3"找不到要删除的对象。"
我使用Realm来管理数据库,我将数据写入其中然后我可以检索它。
当我添加它时,打印的HQuantitySample是:
to be added: 30 mg (2017-10-06 18:36:25 -0400 - 2017-10-06 18:36:25 -0400)
当我删除同一个时,打印的HQuantitySample是:to be deleted: 30 mg (2017-10-06 18:36:25 -0400 - 2017-10-06 18:36:25 -0400)
据我所知,它应该检索相同的数据,因为数量和日期都可以。我误解了HealthKit中删除的任何内容
答案 0 :(得分:1)
您无法通过构建具有类似属性的新HKQuantitySample
来删除之前保存的HKQuantitySample
。如果HealthKit中有两个含有相同开始日期,结束日期和数量的咖啡因样本,您希望HealthKit删除哪一个?每个HKObject
都是唯一的,要删除对象,您必须先使用查询找到它,然后将您从查询中获得的对象传递给delete()
。