【问题标题】:Deleting a Water Sample from HealthKit从 HealthKit 中删除水样
【发布时间】:2016-03-10 17:01:08
【问题描述】:

我的应用程序目前允许用户保存WaterIntakeRecords,然后他们使用 Core Data 进行持久化。我可以写信给 HealthKit,将取水记录保存为HKQuantitySample。

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

我在尝试删除样本时遇到了困难。

当用户保存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 的ouncesUS 值,date 参数是WaterIntakeRecords date 属性,即记录的创建日期:

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

【问题讨论】:

    标签: healthkit


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢,艾伦!通过按照您的建议进行操作,我能够纠正我的情况。我查询了 HealthKit 商店,找到了要删除的记录。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多