【问题标题】:Watch os 2.0 beta: access heart beat rateWatch os 2.0 beta:访问心跳率
【发布时间】:2015-08-26 21:14:56
【问题描述】:

Watch OS 2.0 的开发者应该被允许访问心跳传感器...... 我很想尝试一下,并为我的想法构建一个简单的原型,但我在任何地方都找不到有关此功能的信息或文档。

谁能告诉我如何完成这项任务?任何链接或信息将不胜感激

【问题讨论】:

  • 这不是苹果的保密协议吗,你应该在苹果开发者论坛上问这个吗?
  • @Dan 在开发者论坛中我只能找到和我一样困惑的人......我想也许这里的社区可以提供帮助
  • 啊,够远了。我猜随着下一个 watchOS 2.0 beta 的发布,Apple 会改进它的文档。也许您可以提交错误报告?
  • @Dan,请参阅:Should moderators enforce NDAs for software vendors? 及相关问题。 SO 用户或版主不负责监管其他方之间的 NDA。
  • 在探索了 HealthKit 和 Watchkit 之后,我在此链接中注意到了一些观察结果 stackoverflow.com/a/33363644/591811

标签: ios watchkit apple-watch watchos


【解决方案1】:

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末尾的演示中进行了详细描述

【讨论】:

  • 所以基本上我在手表上开始会话,然后我可以在电话上查询,对吧?唯一的问题是数据仅每隔几分钟而不是每隔几秒传输到我的手机......我也在手机上使用quantityTypeForIdentifier HKQuantityTypeIdentifierHeartRate 进行了enableBackgroundDeliveryForType,但这并没有改变任何东西...... :(跨度>
  • "从 HKHealthKit 开始一个流式查询" 这个查询是在手表上运行还是在手机上运行?我可以开始锻炼并在手表上获取心率样本,但在手机上我得到的结果是空的。
  • 在手表上开始查询,因为它有心率传感器。 Healthkit 数据是在手表上收集的,需要一些时间才能同步到手机上,但可以立即在手表上使用。
【解决方案2】:

您可以通过开始锻炼来获取心率数据,并从 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];
}

您还可以在功能中启用 Healthkit。如果您有任何问题,请在下方留言。

【讨论】:

  • 在模拟器中运行此代码并获取心率?
  • 模拟器会给你结果。
  • 这里我收到此错误=>>>错误错误 Domain=com.apple.healthkit Code=5 "授权请求已取消" UserInfo={NSLocalizedDescription=授权请求已取消}
  • 哦,是的,我忘了告诉您,您需要在开始锻炼之前请求访问用户的健康数据。你想要代码吗?
  • 我该怎么做?
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    许多适用于 iOS 的软件套件现在可用于 watchOS,例如 HealthKit。您可以使用 HealthKit (HK) 函数和类来计算消耗的卡路里、查找心率等。您可以使用 HKWorkout 来计算有关锻炼的所有内容并访问相关变量,例如心率,就像您之前使用 iOS 所做的那样。阅读 Apple 的开发者文档以了解 HealthKit。它们可以在 developer.apple.com 中找到。

    【讨论】:

      猜你喜欢
      • 2022-10-12
      • 2016-04-13
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多