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

标签 ios swift ios10 healthkit

我正在尝试获取半小时前的步骤,并且我正在使用讨论的方法 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()

最佳答案

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

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

关于ios - 尝试使用 HealthKit 获取步数,但它总是返回 0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46207248/

相关文章:

cloudkit - 未知参数使用 CloudKit - iOS 10

ios - 以前的 UITableView 中的项目出现在新的 UITableView 中

objective-c - 自定义 MKAnnotation 总是说它是一个 MKUserLocation 类

ios - 按下按钮时如何添加上标?

swift - 无法在 IOS10 中锁定一个 View Controller 的旋转

ios - 本地通知未在 IOS 10 + Swift 2.3 中调用

android - 如何轻松地将大量字符串资源(如国家列表)添加到android? (也适用于任何其他网络/移动语言)

ios - 从使用的类型泛型之一推断泛型类型

swift - 如何为 Realm 构建查询对象

ios - 无法使用类型为 'append' 的参数列表调用 '(String)',其中每个变量都是非可选的