【问题标题】:HealthKit not returning updated infoHealthKit 未返回更新信息
【发布时间】:2016-04-05 00:56:07
【问题描述】:

我一直在尝试向 HealthKit 查询我手机上的步数。这是我尝试过的:

    let endDate = NSDate()
    let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -1, toDate: endDate, options: [])

    let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)

    let query = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: { (query, results, error) in
        if results == nil {
            print("There was an error running the query: \(error)")
            return
        }

        dispatch_async(dispatch_get_main_queue()) {

            //print(results)

            dispatch_async(dispatch_get_main_queue()) {
                let steps = results as! [HKQuantitySample]
                print(steps.count)
                for step in steps {
                    self.stepsLabel.text = String(step.quantity)
                }
            }

        }
    })

    self.healthKitStore.executeQuery(query)

因此,stepsLabel 现在显示“296 计数”。但是,我有更多的步骤。我不知道为什么它没有正确更新。我也看过this postthis one。但是,我没有很好地理解答案。我应该如何确保查询正确更新?感谢您的帮助。

【问题讨论】:

    标签: ios iphone swift healthkit hkobserverquery


    【解决方案1】:

    您只显示最后一个样品的数量。

    假设您有 100 个样本。 您正在使用不同的数量值更新标签 100 次,而您看到的是上次更新的数量值。

    要查看所有选定样本的总和,您必须将所有(相关)样本的所有数量值相加。

    【讨论】:

    • 请注意,使用 HKStatisticsQuery 会更好。它将为您计算总和并处理来自多个来源的重叠数据。例如,如果用户同时拥有 iPhone 和 Apple Watch,则当前代码将重复计算用户的步数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多