我正试图在 HealthKit 中保存一次锻炼。这是我的代码:
__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);
}
}];
}
}];
提示用户许可(并接受)后,此代码创建一个持续 1 小时、燃烧 100 卡路里且距离为 5000 米的运行事件。
将锻炼保存到 HKHealthStore 会得到成功值 YES 和零错误 - 所以在这一点上,我希望它会在那里。
但是,在打开“健康”应用程序时,我无法找到锻炼、距离或燃烧的卡路里。我错过了什么?
最佳答案
这是 iOS 8 中的预期行为。锻炼不会出现在“健康”应用中,但您仍然应该能够查询它们。如果您还使用 -[HKHealthStore addSamples:toWorkout:completion] 保存与该锻炼相关的卡路里/距离样本,则该锻炼的卡路里和距离只会显示在“健康”中。
关于ios - 在 HealthKit 中保存锻炼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25917558/