尝试使用HealthKit获取步骤,但它总是返回0.0

时间:2017-09-13 21:41:14

标签: ios swift ios10 health-kit

我试图从半个小时前开始采取步骤,并且我正在使用所讨论的方法here。以下是我的代码:

func getSteps(completion: @escaping (Double) -> Void) {
    let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

    let now = Date()
    let calendar = Calendar.current
    let halfHourAgoDate = calendar.date(byAdding: .minute, value: -30, to: now)

    if let date = halfHourAgoDate {
        let predicate = HKQuery.predicateForSamples(withStart: date, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0

            guard let result = result else {
                completion(resultCount)
                return
            }

            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: HKUnit.count())
                return
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }

        healthStore.execute(query)

    } else {
        print("Error MainVC, date is being cast as nil")
    }
}

当我真正尝试获取步骤时,这是我的代码:

 var todaysSteps: Double = 0
 getSteps(completion: { (resultCount) -> Void in
                                todaysSteps = resultCount
                            })
 print(todaysSteps) // always comes out to 0.0

然而,每当我运行此代码时,代码返回0.0。我已启用HealthKit,并授权其执行步骤,因此我不确定原因是什么。另请注意,这是我的变量声明:

let healthStore = HKHealthStore()

1 个答案:

答案 0 :(得分:1)

对于遇到相同问题的任何人,您需要在完成处理程序中执行代码,因此:

var todaysSteps: Double = 0
getSteps(completion: { (resultCount) -> Void in
                            print(resultCount)
})