尝试使用 HealthKit 获取步数,但它总是返回 0.0
Trying to get steps using HealthKit but it's always returning 0.0
我正在尝试获取半小时前的步数,我正在使用讨论的方法 。以下是我的代码:
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
然而每当我运行这段代码时,代码returns0.0。我已经启用了 HealthKit,并授权了它的步骤,所以我不确定是什么原因。另请注意,这是在我的变量声明中:
let healthStore = HKHealthStore()
对于遇到相同问题的任何人,您需要在完成处理程序中执行代码,因此:
var todaysSteps: Double = 0
getSteps(completion: { (resultCount) -> Void in
print(resultCount)
})
我正在尝试获取半小时前的步数,我正在使用讨论的方法
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
然而每当我运行这段代码时,代码returns0.0。我已经启用了 HealthKit,并授权了它的步骤,所以我不确定是什么原因。另请注意,这是在我的变量声明中:
let healthStore = HKHealthStore()
对于遇到相同问题的任何人,您需要在完成处理程序中执行代码,因此:
var todaysSteps: Double = 0
getSteps(completion: { (resultCount) -> Void in
print(resultCount)
})