![](/img/trans.png)
[英]Get accelerometer and gyroscope data from apple watch (and not the iphone)?
[英]How to get sensor data from Apple Watch to iPhone?
有沒有辦法從Apple Watch獲取傳感器數據? 例如,如何從Apple Watch連接並獲取心率到我的應用程序? 這些是我在我的應用中需要執行的步驟:
我知道它如何適用於BT上的其他HR監視器。 界面是否類似? 或者應該依靠HealthKit來實現這一目標?
根據raywenderlic.com上的WatchKit常見問題解答 (滾動到“您可以從手表應用程序訪問手表上的心跳傳感器和其他傳感器嗎?”),看起來好像您無法訪問傳感器數據。
不可以。目前Apple Watch上沒有訪問硬件傳感器的API。
我已經制作了自己的鍛煉應用程序(只是為了了解iWatch和iPhone之間的通信是如何工作的)。 我目前正在通過以下方式獲取心率信息。 顯然,這還沒有經過測試,但是一旦你看看HealthKit框架是如何布局的,它就有意義了。
我們知道Apple Watch將通過藍牙與iPhone通信。 如果您閱讀HealthKit文檔的第一段,您將看到:
在iOS 8.0中,系統可以自動將兼容的藍牙LE心率監視器中的數據直接保存到HealthKit存儲中。
由於我們知道Apple Watch將是藍牙設備並且具有心率傳感器,因此我將假設信息存儲在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];
}
確保在取消分配屏幕后停止執行觀察查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.