iOS 获取实时步数
2016-12-29 本文已影响0人
丧心病狂乐
以下是个人理解,如有不对,轻喷:
网上给的大部分方法是调取系统的"健康"APP(HealthKit 库)的数据,但不是调取"运动与健康"(CoreMotion 库)的数据.
而系统的"健康"APP,需要每次打开"健康"APP时才从"运动与健康"更新数据,而如果使用HealthKit库获取步数,因为是从"健康"APP获得步数等数据,所以如果不打开"健康"APP,那么自己的APP获得的数据不是最新的.
因此调用CoreMotion库,从系统的"运动与健康"中获取实时数据,才能保证步数最新
@IBAction func stepAction(_ sender: UIButton) {
if !CMPedometer.isStepCountingAvailable(){
return
}
let calendar = NSCalendar.current
let now = Date.init()
var components = calendar.dateComponents([.year,.month,.day,.hour,.minute,.second], from: now)
components.hour = 0
components.minute = 0
components.second = 0
let startDate = calendar.date(from: components)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate!)
stepcounter.queryPedometerData(from: startDate!, to: endDate!) { [weak self] (pedData, error) in
self?.updateStepCountLabels(data: pedData!)
}
}
func updateStepCountLabels(data : CMPedometerData) {
print(data)
DispatchQueue.main.async {[weak self] in
self?.stepLabel.text = String.init(format: "步数:%@", data.numberOfSteps)
}
}