我希望从1小时前开始从CMpedometer获取步数。
一旦我运行代码,我得到(在其他事情中写入)控制台中的错误和屏幕上的标签我得到“错误”而不是步骤的nuber:
[Generic]消息回复错误(连接无效) 2018-03-16 12:37:19.021110 + 0100
[计步器]检查可用性时无法解析消息!
这是代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Calculation dates for steps 1h ago
//date now
let calendar = Calendar.current //calendar now, to be used in calculating the h in the past
let beforeDate = calendar.date(byAdding: .hour, value: -1, to: Date())
let pedometer = CMPedometer() //define pedometer
pedometer.queryPedometerData(from: beforeDate!, to: Date(), withHandler: { (pedometerData, error) in
if let pedData = pedometerData{
self.dateLabel.text = "Steps:\(pedData.numberOfSteps)"
}else {
self.dateLabel.text = "error)"
print(beforeDate)
}
})
}
如果我尝试打印之前的日期,我会看到“可选”:
可选(2018-03-16 10:19:26 +0000)
虽然另一个日期看起来更正常:
2018-03-16 11:19:26 +0000
答案 0 :(得分:0)
定义beforeDate
,byAdding
returns an optional value时。如果需要非可选值,则需要打开可选项,如下所示:
let beforeDate = Calendar.current.date(byAdding: .hour, value: -1, to: Date())
print(beforeDate) // this is optional
// this is non-optional because you're unwrapping it
if let beforeDate = beforeDate {
// the date is unwrapped and no longer optional
// now you can do what you need to do with it
}
当您在!
之后添加beforeDate
时,据说您正在进行力量解包。如果您打开不存在的值,您的应用程序将崩溃。
您还需要确保在Info.plist文件中有NSMotionUsageDescription
项的条目。
最后,如果您尚未执行此操作,则可能需要在应用中运行已记录步骤的物理设备。如果您在模拟器中,则不会记录任何步骤,这可以解释步骤的nil
值。