Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving workouts in HealthKit

I'm trying to save a workout in HealthKit. Here's my code:

__weak typeof(self) weakSelf = self;

self.healthStore = [[HKHealthStore alloc] init];
[self.healthStore requestAuthorizationToShareTypes:[NSSet setWithObject:[HKWorkoutType workoutType]] readTypes:nil completion:^(BOOL success, NSError *error) {

    if (success){

        HKWorkout *workout = [HKWorkout workoutWithActivityType:HKWorkoutActivityTypeRunning startDate:[NSDate dateWithTimeIntervalSinceNow:-3600] endDate:[NSDate date] duration:3600 totalEnergyBurned:[HKQuantity quantityWithUnit:[HKUnit calorieUnit] doubleValue:100.0] totalDistance:[HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:5000.0] metadata:nil];

        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.healthStore saveObject:workout withCompletion:^(BOOL success, NSError *error) {
            NSLog(@"Success? %d", success);
            if (error){
                NSLog(@"Error: %@", error);
            }
        }];
    }

}];

After prompting the user for permission (and accepting), this code creates a running activity that lasts for 1 hour, burns 100 calories and has a distance of 5000m.

Saving the workout to the HKHealthStore gives a success value of YES, and a nil error - so at this point, I'd expect it would be there.

However, on opening the Health app I'm unable to find the workout, distance or calories burned. What am I missing?

like image 704
simonmaddox Avatar asked Jan 09 '23 19:01

simonmaddox


1 Answers

This is expected behavior in iOS 8. Workouts do not appear in the Health app, but you should still be able to query for them. Calories and distance from a workout will only show up in Health if you also save calorie/distance samples associated with that workout by using -[HKHealthStore addSamples:toWorkout:completion].

like image 161
Allan Avatar answered Jan 20 '23 00:01

Allan