1

我想删除我的应用在 Health App 中为某个 HKQuantityType 保存的所有 HKQuantitySamples,我该怎么做?

我可以在 Apple 文档中看到函数 deleteObject:withCompletion:,但我并不真正了解如何使用它。有人可以举个例子吗?

编辑:我现在使用以下代码进行删除:

我已将我的食物信息保存为 HKCorrelation,并在 Correlations 元数据 HKMetadataKeyExternalUUID 键中设置我的本地食物 ID。

对于删除,我正在获取 startDate 和 endDate 之间的所有 HKCorrelation 对象,然后如果这些获取的对象之一与我正在寻找的本地食品 ID 匹配:-我删除该 Correlation 中的每个对象,-然后删除 Correlation 本身

HKCorrelationType *foodType = [HKObjectType correlationTypeForIdentifier:HKCorrelationTypeIdentifierFood];

NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:foodType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
    if (!results) {
        NSLog(@"An error occured fetching the user's tracked food. In your app, try to handle this gracefully. The error was: %@.", error);

        return;
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        for (HKCorrelation *foodCorrelation in results) {
            if([[foodCorrelation.metadata valueForKey:HKMetadataKeyExternalUUID] isEqualToString:food_id_I_want_to_delete]) {
                NSSet *objs = foodCorrelation.objects;
                for (HKQuantitySample *sample in objs) {
                    [self.healthStore deleteObject:sample withCompletion:^(BOOL success, NSError *error) {
                        if (success) {
                            NSLog(@"Success. delete sample");
                        }
                        else {
                            NSLog(@"delete: An error occured deleting the sample. In your app, try to handle this gracefully. The error was: %@.", error);
                        }
                    }];
                }

                [self.healthStore deleteObject:foodCorrelation withCompletion:^(BOOL success, NSError *error) {
                    if (success) {
                        NSLog(@"Success. delete %@", [foodCorrelation.metadata valueForKey:HKMetadataKeyExternalUUID]);
                    }
                    else {
                        NSLog(@"delete: An error occured deleting the Correlation. In your app, try to handle this gracefully. The error was: %@.", error);
                    }
                }];
                return;
            }
        }
    });
}];

[self.healthStore executeQuery:query];
4

0 回答 0