从 HealthKit 中删除水样

Deleting a Water Sample from HealthKit

我的应用程序目前允许用户保存 WaterIntakeRecords,然后它们与 Core Data 保持一致。我可以写入 HealthKit,将饮水记录保存为 HKQuantitySample

我在我的应用程序中添加了一个 WaterIntakeRecord,用量为 12.9 液体盎司。由于在健康中,我将毫升作为我的首选测量单位,因此以毫升显示:

我最纠结的地方是在尝试删除样本时。

当用户保存 WaterIntakeRecord 时,他们可以选择他们想要保存样本的计量单位,然后将该计量单位转换为美制盎司,即 属性 WaterIntakeRecord 个。这样,每个 WaterIntakeRecord 都有一个一致的度量单位,可以转换为其他度量单位(所有在 Health 中找到的单位)进行显示。

尝试删除保存的样本时,我尝试这样做:

static func deleteWaterIntakeSampleWithAmount(amount: Double, date: NSDate) {

    guard let type = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater) else {
        print("———> Could not retrieve quantity type for identifier")
        return
    }

    let quantity = HKQuantity(unit: HKUnit.fluidOunceUSUnit(), doubleValue: amount)

    let sample = HKQuantitySample(type: type, quantity: quantity, startDate: date, endDate: date)

    HealthKitStore.deleteObject(sample) { (success, error) -> Void in
        if let err = error {
            print("———> Could not delete water intake sample from HealthKit: \(err)")
        } else {
            print("———> Deleted water intake sample from HealthKit")
        }
    }
}

当用户在我的应用程序中删除一条记录时,它应该删除HealthKit中相应的样本。该记录已成功从我的应用程序中删除,但是,当我尝试使用上述方法从 HealthKit 中删除样本时,我一直收到错误消息:

Error Domain=com.apple.healthkit Code=100 "Transaction failure." UserInfo {NSLocalizedDescription=Transaction failure.}

我不确定我做错了什么导致一直收到此错误。

amount参数是WaterIntakeRecordouncesUS值,date参数是WaterIntakeRecorddate属性 这是记录的创建日期:

关于我在哪里导致删除失败有什么想法吗?

HealthKit 中的每个样本都是独一无二的。删除样本时,您必须先查询您的应用最初保存的样本,然后在调用 HealthKitStore.deleteObject() 时使用它。在上面的代码片段中,您正在创建一个新的、未保存的示例,然后试图将其删除。

确实,在删除之前必须从健康存储中查询和检索样本。下面是我在 obj-c 中使用的代码,作为新手入门的代码:

// get an instance of the health store
self.healthStore = [[HKHealthStore alloc] init];

// the interval of the samples to delete (i observed that for a specific value if start and end date are equal the query doesn't return any objects)
NSDate *startDate = [dateOfSampleToDelete dateByAddingTimeInterval:0];
NSDate *endDate = [dateOfSampleToDelete dateByAddingTimeInterval:1];

// the type you're trying to delete (this could be heart-beats/steps/water/calories/etc..)
HKQuantityType *waterType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryWater];

// the predicate used to execute the query
NSPredicate *queryPredicate = [HKSampleQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];

// prepare the query
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:waterType predicate:queryPredicate limit:100 sortDescriptors:nil resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {

    if (error) {

        NSLog(@"Error: %@", error.description);

    } else {

        NSLog(@"Successfully retreived samples");

        // now that we retrieved the samples, we can delete it/them
        [self.healthStore deleteObject:[results firstObject] withCompletion:^(BOOL success, NSError * _Nullable error) {

            if (success) {

                NSLog(@"Successfully deleted entry from health kit");

            } else {

                NSLog(@"Error: %@", error.description);

            }
        }];

    }
}];

// last but not least, execute the query
[self.healthStore executeQuery:query];

更好的做法是在执行上述解决方案的 [results firstObject] 部分之前检查我们是否确实有要删除的对象