WatchOS2 Health Kit - 添加到活动移动环

时间:2015-09-28 06:00:12

标签: objective-c watch-os-2 health-kit

我正在使用HealthKit创建一个小测试应用程序,试图在活动圈中包含手动锻炼。

我的代码位于屏幕截图下方。

从下面的图片中,178 Cal Other Workout和83 Cal Rower是从Watch Workout App创建的,两者都显示旁边的绿色圆圈(表示它们包含在圆圈中)。

第3次锻炼" 188 Cal Outdoor Run"是从我的测试应用程序创建的,但显示了应用程序图标,没有绿色环,并且不包含在圈子中?

注意:在更新到iOS 9.0.1之前,现在已经放置了应用程序图标的NOTHING。

代码:

HKQuantity *kCal = [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit] doubleValue:188];
HKQuantity *disance = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:2000];

NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow:-3600];
NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:-60];

HKWorkout *workout = [HKWorkout workoutWithActivityType:HKWorkoutActivityTypeRunning startDate:startDate endDate:endDate duration:3540 totalEnergyBurned:kCal totalDistance:disance metadata:nil];

[self.healthStore saveObject:workout withCompletion:^(BOOL success, NSError * _Nullable error) {

    HKQuantity *heartRateForInterval = [HKQuantity quantityWithUnit:[HKUnit unitFromString:@"count/min"] doubleValue:95.0];

    HKQuantitySample *heartRateForIntervalSample = [HKQuantitySample quantitySampleWithType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]
                                    quantity:heartRateForInterval
                                   startDate:startDate
                                     endDate:[NSDate dateWithTimeInterval:60 sinceDate:startDate]];

    __weak typeof(self) weakSelf = self;

    if(!success)
    {
        [self.statusLabel setText:[NSString stringWithFormat:@"saveObject: %@", error.localizedDescription]];
    }
    else
    {
        [self.statusLabel setText:[NSString stringWithFormat:@"Success"]];

        [self.healthStore addSamples:@[heartRateForIntervalSample] toWorkout:workout completion:^(BOOL success, NSError * _Nullable error) {

            if(success) {
                [weakSelf.statusLabel setText:@"Saved - Added Sample"];
            } else {
                [weakSelf.statusLabel setText:[NSString stringWithFormat:@"addSamples: %@", error.localizedDescription]];
            }

        }];
    }

}];

1 个答案:

答案 0 :(得分:0)

仅为totalEnergyBurned属性保存非零HKQuantity的锻炼是不够的。您的应用还必须将相关的活动能量燃烧样本添加到锻炼中,以便计入移动环。有关addSamples:toWorkout:completion:方法,请参阅HKHealthStore文档。理想情况下,活动能量样本应该是细粒度的,以便用户可以在锻炼过程中看到强度的变化。