观看os 2.0 beta:访问心跳率

时间:2015-06-11 09:08:07

标签: ios watchkit apple-watch watch-os

使用Watch OS 2.0开发人员应该被允许访问心跳传感器.... 我很想玩它并为我的想法构建一个简单的原型,但我无法找到有关此功能的任何信息或文档。

有人能指出我如何处理这项任务吗?任何链接或信息将不胜感激

4 个答案:

答案 0 :(得分:32)

从技术上讲,Apple并没有让开发人员访问watchOS 2.0中的心率传感器。他们正在做的是直接访问HealthKit中传感器记录的心率数据。要做到这一点并近乎实时地获取数据,您需要做两件事。首先,你需要告诉手表你正在开始锻炼(假设你正在跑步):

// Create a new workout session
self.workoutSession = HKWorkoutSession(activityType: .Running, locationType: .Indoor)
self.workoutSession!.delegate = self;

// Start the workout session
self.healthStore.startWorkoutSession(self.workoutSession!)

然后,您可以从HKHealthKit启动流式查询,以便在HealthKit收到更新时为您提供更新:

// This is the type you want updates on. It can be any health kit type, including heart rate.
let distanceType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)

// Match samples with a start date after the workout start
let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: .None)

let distanceQuery = HKAnchoredObjectQuery(type: distanceType!, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in
    // Handle when the query first returns results
    // TODO: do whatever you want with samples (note you are not on the main thread)
}

// This is called each time a new value is entered into HealthKit (samples may be batched together for efficiency)
distanceQuery.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
    // Handle update notifications after the query has initially run
    // TODO: do whatever you want with samples (note you are not on the main thread)
}

// Start the query
self.healthStore.executeQuery(distanceQuery)

视频末尾的演示What's New in HealthKit - WWDC 2015

中详细介绍了这一点

答案 1 :(得分:5)

您可以通过开始锻炼并从healthkit查询心率数据来获取心率数据。

要求预先阅读锻炼数据。

HKHealthStore *healthStore = [[HKHealthStore alloc] init];
HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
HKQuantityType *type2 = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
HKQuantityType *type3 = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];

[healthStore requestAuthorizationToShareTypes:nil readTypes:[NSSet setWithObjects:type, type2, type3, nil] completion:^(BOOL success, NSError * _Nullable error) {

    if (success) {
        NSLog(@"health data request success");

    }else{
        NSLog(@"error %@", error);
    }
}];

在iPhone上的AppDelegate中,回应此请求

-(void)applicationShouldRequestHealthAuthorization:(UIApplication *)application{

[healthStore handleAuthorizationForExtensionWithCompletion:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        NSLog(@"phone recieved health kit request");
    }
}];
}

然后实施Healthkit代表:

-(void)workoutSession:(HKWorkoutSession *)workoutSession didFailWithError:(NSError *)error{

NSLog(@"session error %@", error);
}

-(void)workoutSession:(HKWorkoutSession *)workoutSession didChangeToState:(HKWorkoutSessionState)toState fromState:(HKWorkoutSessionState)fromState date:(NSDate *)date{

dispatch_async(dispatch_get_main_queue(), ^{
switch (toState) {
    case HKWorkoutSessionStateRunning:

        //When workout state is running, we will excute updateHeartbeat
        [self updateHeartbeat:date];
        NSLog(@"started workout");
    break;

    default:
    break;
}
});
}

现在是时候写 [self updateHeartbeat:date]

-(void)updateHeartbeat:(NSDate *)startDate{

__weak typeof(self) weakSelf = self;

//first, create a predicate and set the endDate and option to nil/none 
NSPredicate *Predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:nil options:HKQueryOptionNone];

//Then we create a sample type which is HKQuantityTypeIdentifierHeartRate
HKSampleType *object = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

//ok, now, create a HKAnchoredObjectQuery with all the mess that we just created.
heartQuery = [[HKAnchoredObjectQuery alloc] initWithType:object predicate:Predicate anchor:0 limit:0 resultsHandler:^(HKAnchoredObjectQuery *query, NSArray<HKSample *> *sampleObjects, NSArray<HKDeletedObject *> *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {

if (!error && sampleObjects.count > 0) {
    HKQuantitySample *sample = (HKQuantitySample *)[sampleObjects objectAtIndex:0];
    HKQuantity *quantity = sample.quantity;
    NSLog(@"%f", [quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]]);
}else{
    NSLog(@"query %@", error);
}

}];

//wait, it's not over yet, this is the update handler
[heartQuery setUpdateHandler:^(HKAnchoredObjectQuery *query, NSArray<HKSample *> *SampleArray, NSArray<HKDeletedObject *> *deletedObjects, HKQueryAnchor *Anchor, NSError *error) {

 if (!error && SampleArray.count > 0) {
    HKQuantitySample *sample = (HKQuantitySample *)[SampleArray objectAtIndex:0];
    HKQuantity *quantity = sample.quantity;
    NSLog(@"%f", [quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]]);
 }else{
    NSLog(@"query %@", error);
 }
}];

//now excute query and wait for the result showing up in the log. Yeah!
[healthStore executeQuery:heartQuery];
}

您还可以使用健康套件。如果您有任何问题,请在下面发表评论。

答案 2 :(得分:1)

您可以使用HKWorkout,它是HealthKit框架的一部分。

答案 3 :(得分:0)

iOS的许多软件包现在都可用于watchOS,例如HealthKit。您可以使用HealthKit(HK)功能和类来计算燃烧的卡路里,查找心率等。您可以使用HKWorkout计算有关锻炼的所有内容并访问相关变量(如心率),就像之前使用iOS一样。阅读Apple的开发人员文档,以了解HealthKit。它们可以在developer.apple.com上找到。