以下是個人理解,如有不對,輕噴:
網(wǎng)上給的大部分方法是調(diào)取系統(tǒng)的"健康"APP(HealthKit 庫)的數(shù)據(jù),但不是調(diào)取"運動與健康"(CoreMotion 庫)的數(shù)據(jù).
而系統(tǒng)的"健康"APP,需要每次打開"健康"APP時才從"運動與健康"更新數(shù)據(jù),而如果使用HealthKit庫獲取步數(shù),因為是從"健康"APP獲得步數(shù)等數(shù)據(jù),所以如果不打開"健康"APP,那么自己的APP獲得的數(shù)據(jù)不是最新的.
因此調(diào)用CoreMotion庫,從系統(tǒng)的"運動與健康"中獲取實時數(shù)據(jù),才能保證步數(shù)最新
@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: "步數(shù):%@", data.numberOfSteps)
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。