从 Health Kit 获取更新的心率数据

Getting updated heart rate data from Health Kit

我写这段代码是为了获取心率我正在使用 NSArray 并获取心率的平均值。 现在的问题是 Apple Watch 正在更新 Health Kit 中的数据,我希望每 1 分钟刷新一次更新后的平均心跳。 我现在卡住了,请帮忙?

-(double)get_heartRates
{

//code to get the updated heart beats
NSDate *startDate1 = [NSDate distantPast];
NSPredicate *Predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionStrictEndDate];
HKSampleType *object = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

sum_Of_HeartRates=0.0;

HKAnchoredObjectQuery  *heartQuery = [[HKAnchoredObjectQuery alloc] initWithType:object predicate:Predicate anchor:self.lastAnchor limit:0 resultsHandler:^(HKAnchoredObjectQuery *query, NSArray<HKSample *> *sampleObjects, NSArray<HKDeletedObject *> *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {

    NSLog(@"Sample counts:%ld",sampleObjects.count);
    for(int i=0;i<(int)sampleObjects.count;i++)
    {

        HKQuantitySample *sample = (HKQuantitySample *)[sampleObjects objectAtIndex:i];
        HKQuantity *quantity = sample.quantity;
        double bpm_Values= [quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]];
        sum_Of_HeartRates=sum_Of_HeartRates+bpm_Values;

    }
    avg_heartBeats=sum_Of_HeartRates/(int)sampleObjects.count;
}];

[heartQuery setUpdateHandler:^(HKAnchoredObjectQuery *query, NSArray<HKSample *> *SampleArray, NSArray<HKDeletedObject *> *deletedObjects, HKQueryAnchor *Anchor, NSError *error) {

    HKQuantitySample *sample = (HKQuantitySample *)[SampleArray objectAtIndex:0];
    HKQuantity *quantity = sample.quantity;
    new_Updated_Data =[quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]];
    NSLog(@"new quantity:%f",new_Updated_Data);
}];

[self.healthStore executeQuery:heartQuery];
NSLog(@"updated data %f",new_Updated_Data);


return avg_heartBeats;


//todo:- to get background update fast and easy

}

使用 HKObserverQuery 获取在后台更新的长 运行 查询:

https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKObserverQuery_Class/index.html

只要 HKWorkoutSession 不是 运行,您的手表就会每 10 分钟测量一次心率,因此您不会获得更多值。当手表上的 HKWorkoutSession 为 运行 时,您会更频繁地获取值。

如果你想深入HKWorkoutSession,Allan有详细的教程:https://developer.apple.com/videos/play/wwdc2015/203/