1
private func readDataFromHealthKit(_ forIdentifier: HKQuantityTypeIdentifier,_ completionHandler : @escaping (Double?,NSError?) -> Void) {

    let endDate = currentDate 
    let startDate = calendar.startOfDay(for: currentDate)

    let type = HKSampleType.quantityType(forIdentifier: forIdentifier)
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
    // The actual HealthKit Query which will fetch all of the steps and sub them up for us.
    let statisticsQuery = HKStatisticsQuery(quantityType: type!, quantitySamplePredicate: predicate, options: .cumulativeSum) { (query, results, error) in
        var resultCount = 0.0
        if let result = results?.sumQuantity() {
            if forIdentifier == .distanceWalkingRunning {
                resultCount = result.doubleValue(for: HKUnit.meter())
            } else {
                resultCount = result.doubleValue(for: HKUnit.count())
            }
        }
        completionHandler(resultCount,nil)
    }
    healthKitStore.execute(statisticsQuery)
}

我正在从 healthkit 获取步数和距离。当我第一次调用这个函数时,我得到了错误的值。但是,如果再次调用此函数,我会得到正确的结果。

4

0 回答 0