Ios 从CMPedometer检索数据时出现问题:“;回复消息时出错(连接无效)";
我试图使用CoreMotion的CMPedometer获取步数,但我在日志中得到了以下错误,而不是步数:消息回复错误(连接无效)。下面的示例在设备上运行(不是模拟器) 代码(ViewController.swift中的viewDidLoad内部): 日志:Ios 从CMPedometer检索数据时出现问题:“;回复消息时出错(连接无效)";,ios,swift,core-motion,Ios,Swift,Core Motion,我试图使用CoreMotion的CMPedometer获取步数,但我在日志中得到了以下错误,而不是步数:消息回复错误(连接无效)。下面的示例在设备上运行(不是模拟器) 代码(ViewController.swift中的viewDidLoad内部): 日志: 似乎let pedometer=CMPedometer()必须是非本地的,例如在viewDidLoad的之外的类中声明。几乎所有代码: @IBOutlet weak var stepLabel: UILabel! let pedometer
似乎
let pedometer=CMPedometer()
必须是非本地的,例如在viewDidLoad的之外的类中声明。几乎所有代码:
@IBOutlet weak var stepLabel: UILabel!
let pedometer = CMPedometer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if CMPedometer.isStepCountingAvailable() {
print("Step counting is available...")
let calendar = Calendar.current
var toDate = Date()
var fromDate = calendar.startOfDay(for: toDate)
fromDate = calendar.date(byAdding: .hour, value: -24, to: fromDate)!
toDate = calendar.date(byAdding: .hour, value: 2, to: toDate)!
print("From date = \(fromDate)")
print("To date = \(toDate)")
pedometer.queryPedometerData(from: fromDate, to: toDate) { (data, error) in
print("Handler (data):")
print(data!)
guard let activityData = data, error == nil else {
print("There was an error getting the data: \(error!)")
return
}
DispatchQueue.main.async {
self.stepLabel.text = "Steps and distance: \(activityData.numberOfSteps) \(activityData.distance ?? -1)"
}
}
}
}
Step counting is available...
From date = 2019-06-15 22:00:00 +0000
To date = 2019-06-15 22:48:35 +0000
2019-06-16 00:48:40.827268+0200 StepTest2[3857:1087379] [Generic_deprecated] Error on message reply (Connection invalid)
@IBOutlet weak var stepLabel: UILabel!
let pedometer = CMPedometer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if CMPedometer.isStepCountingAvailable() {
print("Step counting is available...")
let calendar = Calendar.current
var toDate = Date()
var fromDate = calendar.startOfDay(for: toDate)
fromDate = calendar.date(byAdding: .hour, value: -24, to: fromDate)!
toDate = calendar.date(byAdding: .hour, value: 2, to: toDate)!
print("From date = \(fromDate)")
print("To date = \(toDate)")
pedometer.queryPedometerData(from: fromDate, to: toDate) { (data, error) in
print("Handler (data):")
print(data!)
guard let activityData = data, error == nil else {
print("There was an error getting the data: \(error!)")
return
}
DispatchQueue.main.async {
self.stepLabel.text = "Steps and distance: \(activityData.numberOfSteps) \(activityData.distance ?? -1)"
}
}
}
}