2014-09-18 105 views
4

我試圖在HealthKit中保存鍛鍊。這裏是我的代碼:在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的成功值,並且一個零錯誤 - 所以在這一點上,我希望它會在那裏。

但是,在打開健康應用程序時,我無法找到鍛鍊,距離或消耗的卡路里。我錯過了什麼?

回答

8

這是iOS 8中的預期行爲。體育鍛煉不會出現在Health應用程序中,但您仍應該能夠查詢它們。如果您還通過使用- [HKHealthStore addSamples:toWorkout:completion],還可以保存卡路里和健身距離,那麼您只需在Health中保存卡路里/距離樣本。

+0

謝謝!我也提出這個作爲「功能要求」雷達 - rdar:// 18391800 – simonmaddox 2014-09-19 08:13:51

+0

快速的問題...一旦你'addSamples:toWorkout' ...你怎麼能再次得到它們? – Georg 2017-04-05 16:16:51