我的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)
}
請包含代碼片段,演示如何計算用戶正在使用的步數。你使用哪種類型的查詢? – Allan
@Allan我更新了我的問題以包含我用來計算用戶步驟的代碼。 – owlswipe