2015-04-06 200 views
8

有沒有辦法從Apple Watch獲取傳感器數據?例如,我怎樣才能連接並從蘋果手錶獲取心率到我的應用程序?這些都是我需要做我的應用程序的步驟:如何從Apple Watch獲取傳感器數據到iPhone?

  1. 定義委託從Apple關注接收心臟速率信息。
  2. 讓蘋果觀看請求發送數據定期

我知道它是如何工作的其他人力資源監視器在BT。界面是否與此類似?還是應該依靠HealthKit來實現?

+0

[Apple Watch上的心率數據]的可能重複(http://stackoverflow.com/questions/28858667/heart-rate-data-on-apple-watch) – bmike 2015-07-01 15:49:39

回答

4

根據WatchKit FAQ on raywenderlich.com(滾動到「您可以通過手錶應用程序訪問手錶上的心跳傳感器和其他傳感器嗎?」),看起來好像無法訪問傳感器數據。

不。目前沒有API訪問 Apple Watch上的硬件傳感器。

3

我做了自己的鍛鍊應用程序(只是爲了瞭解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]; 
} 

確保停止執行,一旦畫面被釋放的觀察查詢。

相關問題