Health与HealthKit-swift处理多个步骤源

我的Swift iOS应用程序与HealthKit连接,向用户显示当天到目前为止所采取的步骤。 大多数情况下,这是成功的。 当步骤的唯一来源是iPhone的内置计步器functionlogging的步骤时,一切工作正常,我的应用程序显示的步数与健康应用程序的步数相匹配。 但是,当我的个人iPhone上有多个数据源时,我的Pebble Time智能手表和iPhone的计步器都会向Health提供步骤 – 我的应用程序吓坏了,logging了两者的所有步骤。 鉴于iOS健康应用程序根源重复的步骤(它可以做,因为我的iPhone和我的卵石报告每隔60秒步骤健康),并显示一个准确的每日步数,我的应用程序从HealthKit获得的数据包括所有从这两个步骤来源,造成很大的不准确。

我怎样才能进入健康应用程序的最终结果,其步数是准确的,而不是进入HealthKit的过度膨胀的步骤数据stream?

更新 :这是我用来获取每日健康数据的代码:

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) } 

您的代码是过度计数的步骤,因为它只是将HKSampleQuery的结果HKSampleQuery 。 示例查询将返回与给定谓词匹配的所有样本,包括来自多个来源的重叠样本。 如果您想使用HKSampleQuery准确地计算用户的步数,那么您必须检测重叠的样本并避免对它们进行计数,这样做会很繁琐而且难以正确执行。

运行状况使用HKStatisticsQueryHKStatisticsCollectionQuery来计算聚合值。 这些查询为你计算总和(和其他总值),并且这样做是有效的。 最重要的是,他们去重复重叠的样本,以避免重复计算。

HKStatisticsQuery的文档包含示例代码。