WWDC 2014 Session 612 (45:14)重点介绍了如何检查Core Motion Services的授权状态:
- (void)checkAuthorization:(void (^)(BOOL authorized))authorizationCheckCompletedHandler {
NSDate *now = [NSDate date];
[_pedometer queryPedometerDataFromDate:now toDate:now withHandler:^(CMPedometerData *pedometerData, NSError *error) {
// Because CMPedometer dispatches to an arbitrary queue, it's very important
// to dispatch any handler block that modifies the UI back to the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
authorizationCheckCompletedHandler(!error || error.code != CMErrorMotionActivityNotAuthorized);
});
}];
}
虽然这有效,但第一次调用-queryPedometerDataFromDate:toDate:withHandler:
将通过系统对话框提示用户进行授权。我更愿意检查状态,而不必向用户请求明显的UX原因。
我想要实现的是什么,或者我只是想错误的API?
对于iOS 11:使用CMPedometer.authorizationStatus()方法。通过调用此方法,您可以确定您是否被授权,拒绝,限制或未确定。
https://developer.apple.com/documentation/coremotion/cmpedometer/2913743-authorizationstatus
对于运行iOS 9-10的设备,请使用CMSensorRecorder.isAuthorizedForRecording()。
这是一个适用于运行iOS 9-11的所有设备的方法:
var isCoreMotionAuthorized: Bool {
if #available(iOS 11.0, *) {
return CMPedometer.authorizationStatus() == .authorized
} else {
// Fallback on earlier versions
return CMSensorRecorder.isAuthorizedForRecording()
}
}
[stepCounter queryStepCountStartingFrom:[NSDate date]
to:[NSDate date]
toQueue:[NSOperationQueue mainQueue]
withHandler:^(NSInteger numberOfSteps, NSError *error) {
if (error != nil && error.code == CMErrorMotionActivityNotAuthorized) {
// The app isn't authorized to use motion activity support.
如果应用程序未被授权访问Core Motion数据,此方法将允许您通知用户。只需创建一个名为stepCounter的CMPedometer
实例并运行上面的方法。