我想删除我的应用程序在Health App中为某个HKQuantityType保存的所有HKQuantitySamples,我该怎么做?
我可以看到这个功能 DeleteObject的:withCompletion: 在Apple文档中,但我真的不明白如何使用它。有人可以展示一个例子吗?
编辑:我现在使用以下代码进行删除:
我已将食物信息保存为HKCorrelation,并在Correlations元数据HKMetadataKeyExternalUUID键中设置我的本地食物ID。
要删除,我将在startDate和endDate之间获取所有HKCorrelation对象,然后如果其中一个获取的对象与我正在寻找的Local Food ID匹配: - 我删除了相关中的每个对象, - 然后删除相关本身
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];