10月7日更新
因此,在阅读完答案后,我现在明白我需要使用查询来检索 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 块中没有做很多事情,我首先想检查我找到了什么数据,当我打印数量时,我注意到了,但我确实得到了“Here we got not nil on resluts”,这意味着结果不是零。我对 iOS 开发很陌生,我检查了 HKHealthSample 的文档,找不到我的 HKSampleQuery 的哪一部分错误!
原创一:
我有一个应用程序可以通过 HealthKit 将咖啡因数据写入 Health 这是保存功能
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 "Failed to find some objects for delete."
我使用 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 中的删除有什么误解吗