Ios 如何从Apple Watch到iPhone获取传感器数据?
有没有办法从Apple Watch获取传感器数据?例如,我如何将Apple Watch连接到我的应用程序并获取心率?以下是我需要在我的应用程序中执行的步骤:Ios 如何从Apple Watch到iPhone获取传感器数据?,ios,watchkit,healthkit,Ios,Watchkit,Healthkit,有没有办法从Apple Watch获取传感器数据?例如,我如何将Apple Watch连接到我的应用程序并获取心率?以下是我需要在我的应用程序中执行的步骤: 定义一个代理以从Apple Watch接收心率信息 向Apple Watch发出定期发送数据的请求 我知道它是如何在BT上为其他人力资源监控器工作的。界面与此类似吗?或者应该依靠HealthKit来实现这一点?根据(滚动至“您可以从手表应用程序访问手表上的心跳传感器和其他传感器吗?”)它显示为您无法访问传感器数据 不存在。当前没有API来访
我制作了自己的锻炼应用程序(只是为了了解iWatch和iPhone之间的通信是如何工作的)。我目前通过以下方式获取心率信息。显然,这还没有经过测试,但一旦您了解HealthKit框架是如何布局的,它就有了意义 我们知道Apple Watch将通过蓝牙与iPhone通信。如果您阅读HealthKit文档的第一段,您将看到: 在iOS 8.0中,系统可以自动保存来自兼容服务器的数据 蓝牙LE心率监测器直接进入HealthKit商店 因为我们知道苹果手表将是一个蓝牙设备,并且有一个心率传感器,所以我假设信息存储在HealthKit中 因此,我编写了以下代码:
- (void) retrieveMostRecentHeartRateSample: (HKHealthStore*) _healthStore completionHandler:(void (^)(HKQuantitySample*))completionHandler
{
HKSampleType *_sampleType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
NSPredicate *_predicate = [HKQuery predicateForSamplesWithStartDate:[NSDate distantPast] endDate:[NSDate new] options:HKQueryOptionNone];
NSSortDescriptor *_sortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierStartDate ascending:NO];
HKSampleQuery *_query = [[HKSampleQuery alloc] initWithSampleType:_sampleType predicate:_predicate limit:1 sortDescriptors:@[_sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error)
{
if (error)
{
NSLog(@"%@ An error has occured with the following description: %@", self, error.localizedDescription);
}
else
{
HKQuantitySample *mostRecentSample = [results objectAtIndex:0];
completionHandler(mostRecentSample);
}
}];
[_healthStore executeQuery:_query];
}
static HKObserverQuery *observeQuery;
- (void) startObservingForHeartRateSamples: (HKHealthStore*) _healthStore completionHandler:(void (^)(HKQuantitySample*))_myCompletionHandler
{
HKSampleType *_sampleType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
if (observeQuery != nil)
[_healthStore stopQuery:observeQuery];
observeQuery = [[HKObserverQuery alloc] initWithSampleType:_sampleType predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error)
{
if (error)
{
NSLog(@"%@ An error has occured with the following description: %@", self, error.localizedDescription);
}
else
{
[self retrieveMostRecentHeartRateSample:_healthStore completionHandler:^(HKQuantitySample *sample)
{
_myCompletionHandler(sample);
}];
// If you have subscribed for background updates you must call the completion handler here.
// completionHandler();
}
}];
[_healthStore executeQuery:observeQuery];
}
取消分配屏幕后,确保停止执行观察查询。可能重复的