What is the cause of this HealthKit error: “An error occurred while adding a sample to the workout”?

醉酒当歌 提交于 2019-12-08 04:37:54

问题


I understand why, but the ambiguity of the errors that HealthKit puts out is a total black box. Why am I getting the error:

An error occurred while adding a sample to the workout: The operation couldn’t be completed.

I've been scouring the web for examples, but most of them are in swift. :(

Here's my code:

- (NSSet *)dataTypesToRead {
    HKQuantityType *heartRate = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

    return [NSSet setWithObjects:heartRate, nil];
}

- (NSSet *)dataTypesToWrite {
    HKWorkoutType* workout = [HKWorkoutType workoutType];
    HKQuantityType *energyBurnedType = [HKQuantityType  quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];

    return [NSSet setWithObjects:workout, energyBurnedType, nil];
}

- (void)saveWorkout {

    HKHealthStore* healthStore = [[HKHealthStore alloc] init];

    NSDate* timeOfWorkout = [NSDate date];

    HKWorkoutType* type = [HKWorkoutType workoutType];

    [healthStore requestAuthorizationToShareTypes:[self dataTypesToWrite]
                                        readTypes:[self dataTypesToRead]
                                       completion:^(BOOL success, NSError *error) {

       if(success == YES)
       {
           // This sample uses hard-coded values and performs all the operations inline
           // for simplicity's sake. A real-world app would calculate these values
           // from sensor data and break the operation up using helper methods.

           HKQuantity *energyBurned =
           [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit]
                            doubleValue:333.0];

           HKQuantity *distance =
           [HKQuantity quantityWithUnit:[HKUnit mileUnit]
                            doubleValue:0.0];

           // Provide summary information when creating the workout.
           HKWorkout *workout = [HKWorkout workoutWithActivityType:HKWorkoutActivityTypeTraditionalStrengthTraining
                                                         startDate:timeOfWorkout
                                                           endDate:timeOfWorkout
                                                          duration:0
                                                 totalEnergyBurned:energyBurned
                                                     totalDistance:distance
                                                          metadata:nil];

           // Save the workout before adding detailed samples.
           [healthStore saveObject:workout withCompletion:^(BOOL success, NSError *error) {
               if (!success) {
                   // Perform proper error handling here...
                   NSLog(@"*** An error occurred while saving the "
                         @"workout: %@ ***", error.localizedDescription);

                   abort();
               }

           }];

           // Add optional, detailed information for each time interval
           NSMutableArray *samples = [NSMutableArray array];

           HKQuantityType *energyBurnedType =
           [HKObjectType quantityTypeForIdentifier:
            HKQuantityTypeIdentifierActiveEnergyBurned];


           [samples addObject:energyBurnedType];

           // Add all the samples to the workout.
           [healthStore
            addSamples:samples
            toWorkout:workout
            completion:^(BOOL success, NSError *error) {
                if (!success) {
                    // Perform proper error handling here...
                    NSLog(@"*** An error occurred while adding a "
                          @"sample to the workout: %@ ***",
                          error.localizedDescription);

                    abort();
                }
            }];
       }
       else
       {
           // Determine if it was an error or if the
           // user just canceld the authorization request
       }

   }];
}

回答1:


Here I find 2 issues,

  1. Your trying to add samples to a workout before saving the workout in HealthKit.
  2. Samples array should contain objects of type HKQuantitySample or HKCategorySample.

This is working fine...

- (NSSet *)dataTypesToRead {
    HKQuantityType *heartRate = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

    return [NSSet setWithObjects:heartRate, nil];
}

- (NSSet *)dataTypesToWrite {
    HKWorkoutType* workout = [HKWorkoutType workoutType];
    HKQuantityType *energyBurnedType = [HKQuantityType  quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];

    return [NSSet setWithObjects:workout, energyBurnedType, nil];
}

- (void)saveWorkout {

    HKHealthStore* healthStore = [[HKHealthStore alloc] init];

    NSDate* timeOfWorkout = [NSDate date];

    [healthStore requestAuthorizationToShareTypes:[self dataTypesToWrite]
                                        readTypes:[self dataTypesToRead]
                                       completion:^(BOOL success, NSError *error) {

                                           if(success == YES)
                                           {
                                               // This sample uses hard-coded values and performs all the operations inline
                                               // for simplicity's sake. A real-world app would calculate these values
                                               // from sensor data and break the operation up using helper methods.

                                               HKQuantity *energyBurned =
                                               [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit]
                                                                doubleValue:333.0];

                                               HKQuantity *distance =
                                               [HKQuantity quantityWithUnit:[HKUnit mileUnit]
                                                                doubleValue:0.0];

                                               // Provide summary information when creating the workout.
                                               HKWorkout *workout = [HKWorkout workoutWithActivityType:HKWorkoutActivityTypeTraditionalStrengthTraining
                                                                                             startDate:timeOfWorkout
                                                                                               endDate:timeOfWorkout
                                                                                              duration:0
                                                                                     totalEnergyBurned:energyBurned
                                                                                         totalDistance:distance
                                                                                              metadata:nil];

                                               // Save the workout before adding detailed samples.
                                               [healthStore saveObject:workout withCompletion:^(BOOL success, NSError *error) {
                                                   if (!success) {
                                                       // Perform proper error handling here...
                                                       NSLog(@"*** An error occurred while saving the "
                                                             @"workout: %@ ***", error.localizedDescription);

//                                                       abort();
                                                   }
                                                   else
                                                   {
                                                       // Add optional, detailed information for each time interval
                                                       NSMutableArray *samples = [NSMutableArray array];

                                                       HKQuantityType *energyBurnedType =
                                                       [HKObjectType quantityTypeForIdentifier:
                                                        HKQuantityTypeIdentifierActiveEnergyBurned];

                                                       HKQuantity *energyBurnedQuantity = [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit] doubleValue:334];

                                                       HKQuantitySample *energyBurnedSample = [HKQuantitySample quantitySampleWithType:energyBurnedType quantity:energyBurnedQuantity startDate:[NSDate date] endDate:[NSDate date]];

                                                       [samples addObject:energyBurnedSample];

                                                       // Add all the samples to the workout.
                                                       [healthStore
                                                        addSamples:samples
                                                        toWorkout:workout
                                                        completion:^(BOOL success, NSError *error) {
                                                            if (!success) {
                                                                // Perform proper error handling here...
                                                                NSLog(@"*** An error occurred while adding a "
                                                                      @"sample to the workout: %@ ***",
                                                                      error.localizedDescription);

                                                                //                                                        abort();
                                                            }
                                                        }];

                                                   }

                                               }];

                                           }
                                           else
                                           {
                                               // Determine if it was an error or if the
                                               // user just canceld the authorization request
                                           }

                                       }];
}


来源:https://stackoverflow.com/questions/29068172/what-is-the-cause-of-this-healthkit-error-an-error-occurred-while-adding-a-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!