从HealthKit

时间:2016-03-10 17:01:09

标签: health-kit

我的应用程序目前允许用户保存WaterIntakeRecord,然后使用Core Data保留它们。我可以写入HealthKit,将水摄入记录保存为HKQuantitySample

我在我的应用程序中添加了WaterIntakeRecord,其量为12.9液量盎司。因为在Health,我有毫升作为我的首选测量单位,它以毫升表示:

enter image description here

我正在努力尝试删除样本。

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

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

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参数是WaterIntakeRecord的{​​{1}}值,ouncesUS参数是date s WaterIntakeRecord属性,记录的创建日期:

关于我导致删除失败的任何想法?

2 个答案:

答案 0 :(得分:2)

实际上,在删除之前必须从健康商店查询和检索样本。下面是我在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]部分之前检查我们确实有一个要删除的对象

答案 1 :(得分:1)

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