9

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

如何利用 Health 应用程序的最终结果(步数准确),而不是利用 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)
    }
4

1 回答 1

16

您的代码过多计算步骤,因为它只是简单地将HKSampleQuery. 样本查询将返回与给定谓词匹配的所有样本,包括来自多个来源的重叠样本。如果您想使用 准确计算用户的步数HKSampleQuery,则必须检测重叠样本并避免计算它们,这将是乏味且难以正确执行的。

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

HKStatisticsQuery的文档包括示例代码。

于 2016-04-12T20:35:26.397 回答