以下是個(gè)人理解,如有不對(duì),輕噴:
網(wǎng)上給的大部分方法是調(diào)取系統(tǒng)的"健康"APP(HealthKit 庫(kù))的數(shù)據(jù),但不是調(diào)取"運(yùn)動(dòng)與健康"(CoreMotion 庫(kù))的數(shù)據(jù).
而系統(tǒng)的"健康"APP,需要每次打開(kāi)"健康"APP時(shí)才從"運(yùn)動(dòng)與健康"更新數(shù)據(jù),而如果使用HealthKit庫(kù)獲取步數(shù),因?yàn)槭菑?健康"APP獲得步數(shù)等數(shù)據(jù),所以如果不打開(kāi)"健康"APP,那么自己的APP獲得的數(shù)據(jù)不是最新的.
因此調(diào)用CoreMotion庫(kù),從系統(tǒng)的"運(yùn)動(dòng)與健康"中獲取實(shí)時(shí)數(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)容合作請(qǐng)聯(lián)系作者