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

时间:2016-03-25 06:20:17

标签: ios objective-c apple-watch 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

}

1 个答案:

答案 0 :(得分:0)

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

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

只要没有HKWorkoutSession正在运行,您的手表每10分钟测量一次心率,因此您无法获得更多值。当您的手表上正在运行HKWorkoutSession时,您会更频繁地获得价值。

如果你想深入研究HKWorkoutSession,艾伦有一个详细的教程:https://developer.apple.com/videos/play/wwdc2015/203/