Health 处理多步骤源的方式与 HealthKit 不同—swift

Health handles multiple step sources differently than HealthKit—swift

我的 Swift iOS 应用程序与 HealthKit 连接,向用户显示他们当天到目前为止走了多少步。在大多数情况下,这是成功的。当步数的唯一来源是由 iPhone 的内置计步器功能记录的步数时,一切正常,我的应用程序显示的步数与健康应用程序的步数相匹配。然而,当有多个数据源时——在我的个人 iPhone、我的 Pebble Time 智能手表和 iPhone 的计步器上都向健康提供步数——我的应用程序崩溃了,记录了两者的所有步数. iOS Health 应用程序根除重复的步骤(它可以做到这一点,因为我的 iPhone 和我的 Pebble 每 60 秒报告一次 Health 步数)并显示准确的每日步数,我的应用程序获取的数据来自 HealthKit 的代码包含了来自两个来源的所有步骤,导致了很大的不准确性。

我如何才能利用健康应用程序的最终结果,其中步数是准确的,而不是利用 HealthKit 过度膨胀的步数数据流?

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

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 的结果求和。样本查询将 return 所有与给定谓词匹配的样本,包括来自多个来源的重叠样本。如果您想使用 HKSampleQuery 准确计算用户的步数,您必须检测重叠样本并避免对它们进行计数,这将是乏味且难以正确执行的。

Health 使用 HKStatisticsQueryHKStatisticsCollectionQuery 来计算合计值。这些查询会为您计算总和(和其他聚合值),而且计算效率很高。不过,最重要的是,他们对重叠样本进行了去重以避免过度计数。

documentation for HKStatisticsQuery 包含示例代码。