导致此HealthKit错误的原因是:“将样本添加到锻炼中时发生错误”? [英] What is the cause of this HealthKit error: "An error occurred while adding a sample to the workout"?

查看:169
本文介绍了导致此HealthKit错误的原因是:“将样本添加到锻炼中时发生错误”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解为什么,但HealthKit提出的错误含糊不清是一个完整的黑盒子。为什么我收到错误:

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. :(

这是我的代码:

- (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
       }

   }];
}


推荐答案

这里我找到2个问题,

Here I find 2 issues,


  1. 在HealthKit中保存锻炼之前,您尝试将样本添加到锻炼中。

  2. 样本数组应包含HKQuantitySample或HKCategorySample类型的对象。

  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
                                           }

                                       }];
}

这篇关于导致此HealthKit错误的原因是:“将样本添加到锻炼中时发生错误”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆