2016-04-11 106 views
4

我的Swift iOS應用程序連接HealthKit以向用戶顯示當天到目前爲止他們採取了多少步驟。大多數情況下,這是成功的。當步驟的唯一來源是iPhone內置計步器功能記錄的步驟時,一切正常,我的應用程序顯示的步數與Health應用程序的步數相匹配。但是,當我的個人iPhone上有多個數據源時,我的Pebble Time智能手錶和iPhone的計步器都會向Health提供步驟 - 我的應用程序出現異常,記錄了兩者的所有步驟。鑑於iOS健康應用程序根據重複步驟(它可以做到這一點,因爲我的iPhone和Pebble報告每60秒就會運行一次健康狀況)並顯示準確的每日步數,我的應用程序從HealthKit獲取的數據包括來自兩者的所有步驟來源,造成很大的不準確。Health以不同於HealthKit的方式處理多個步驟源

我怎樣才能進入健康應用程序的最終結果,其中的步數是準確的,而不是進入HealthKit的過度膨脹步驟數據流?

UPDATE:這是我用它來獲取日常保健數據的代碼:

func recentSteps2(completion: (Double, NSError?) ->()) 
    { 

     checkAuthorization() // checkAuthorization just makes sure user is allowing us to access their health data. 
     let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting 


     let date = NSDate() 
     let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! 
     let newDate = cal.startOfDayForDate(date) 
     let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today 

     // The actual HealthKit Query which will fetch all of the steps and add them up for us. 
     let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in 
      var steps: Double = 0 

      if results?.count > 0 
      { 
       for result in results as! [HKQuantitySample] 
       { 
        steps += result.quantity.doubleValueForUnit(HKUnit.countUnit()) 
       } 
      } 

      completion(steps, error) 
     } 

     storage.executeQuery(query) 
    } 
+0

請包含代碼片段,演示如何計算用戶正在使用的步數。你使用哪種類型的查詢? – Allan

+0

@Allan我更新了我的問題以包含我用來計算用戶步驟的代碼。 – owlswipe

回答

8

你的代碼是重複計算步驟,因爲它只是一個概括的HKSampleQuery結果。示例查詢將返回與給定謂詞匹配的所有樣本,包括來自多個來源的重疊樣本。如果您想用HKSampleQuery準確地計算用戶的步數,那麼您必須檢測重疊的樣本並避免對它們進行計數,這會很繁瑣且難以正確執行。

健康使用HKStatisticsQueryHKStatisticsCollectionQuery來計算聚合值。這些查詢爲您計算總和(以及其他總計值),並有效地執行此操作。但最重要的是,他們去重複重疊樣本以避免重複計算。

documentation for HKStatisticsQuery包括示例代碼。

+0

謝謝!我可以獲得更多關於HKStatisticsQuery的信息嗎?也許代碼示例或教程鏈接(我搜索谷歌,它很稀疏)? – owlswipe

+0

您是否嘗試查看參考文檔中的示例代碼? https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKStatisticsQuery_Class/ – Allan