使用HealthKit获取今日步数遇Code=11错误,求解决方法
解决HealthKit获取今日步数时的Code=11错误
错误原因分析
- 授权逻辑错误:你的
authorisationHealthkit()是同步返回权限状态,但HealthKit的授权请求是异步操作,直接返回的access值可能不准确,导致还没拿到权限就执行了查询。另外要确认该方法是否正确请求了HKQuantityTypeIdentifierStepCount的读取权限。 - HealthStore实例不一致:ViewController里自行创建了
healthStore,如果HealthkitManager用的是另一个实例,会导致权限状态不共享。 - 未处理无数据场景:当今日确实没有步数数据时,
statistics会为nil,此时你的代码未调用completion,同时系统会返回Code=11的提示(这是无数据的正常告知,不属于异常错误)。
修正后的完整代码
重构授权逻辑为异步处理,同时统一HealthStore实例:
import UIKit import HealthKit class ViewController: UIViewController { // 统一使用一个HealthStore实例 let healthStore = HKHealthStore() override func viewDidLoad() { super.viewDidLoad() // 异步请求授权 requestHealthKitAuthorization { [weak self] granted in guard granted, let self = self else { return } self.getTodaysSteps { steps in print("今日步数:\(steps)") } } } // 异步请求HealthKit权限 private func requestHealthKitAuthorization(completion: @escaping (Bool) -> Void) { guard HKHealthStore.isHealthDataAvailable() else { print("设备不支持HealthKit") completion(false) return } let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount)! let readTypes: Set<HKObjectType> = [stepCountType] healthStore.requestAuthorization(toShare: nil, read: readTypes) { success, error in if let error = error { print("授权失败:\(error.localizedDescription)") completion(false) return } completion(success) } } // 获取今日步数 func getTodaysSteps(completion: @escaping (Double) -> Void) { guard let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount) else { completion(0) return } let now = Date() let startOfDay = Calendar.current.startOfDay(for: now) let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictEndDate) let query = HKStatisticsQuery(quantityType: stepCountType, quantitySamplePredicate: predicate) { _, statistics, error in DispatchQueue.main.async { if let error = error { // Code=11是无数据提示,无需当成错误处理 print("查询信息:\(error.localizedDescription)") } // 无数据时默认返回0,保证completion总能被调用 let steps = statistics?.sumQuantity()?.doubleValue(for: HKUnit.count()) ?? 0 completion(steps) } } healthStore.execute(query) } }
关键修正点
- 异步授权:使用
HKHealthStore.requestAuthorization的异步回调处理授权结果,避免同步返回的状态不准确。 - 统一HealthStore实例:整个流程使用同一个
healthStore,确保权限状态一致。 - 处理无数据场景:当
statistics为nil时返回0,保证completion总能被触发,同时正确看待Code=11的提示。 - 明确权限范围:直接指定请求
stepCount的读取权限,确保授权逻辑正确。
内容的提问来源于stack exchange,提问作者Sowrya mukkavilli
相关产品推荐
相关产品推荐

