2

WWDC 2014 Session 612 (45:14) highlights how to check the authorization status of 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);
        });
    }];
}

While this works, the first call to -queryPedometerDataFromDate:toDate:withHandler: will prompt the user for authorization via a system dialog. I would prefer to check the status without having to ask the user for permission for obvious UX reasons.

Is what I am trying to achieve possible or am I just thinking about the API the wrong way?

Joe Masilotti
  • 16,815
  • 6
  • 77
  • 87
  • This link should answer your question: http://stackoverflow.com/questions/21005990/ios-is-motion-activity-enabled-in-settings-privacy-motion-activity – Michael Royzen Aug 28 '15 at 05:38
  • @MichaelRoyzen thanks! But "`[CMMotionActivityManager isActivityAvailable]` returns a boolean of whether the device supports the motion data, not if the user has given the app permission to use it." – Joe Masilotti Aug 28 '15 at 11:08

2 Answers2

4

For iOS 11: Use the CMPedometer.authorizationStatus() method. By calling this method, you can determine if you are authorized, denied, restricted or notDetermined.

https://developer.apple.com/documentation/coremotion/cmpedometer/2913743-authorizationstatus

For devices running iOS 9-10, use CMSensorRecorder.isAuthorizedForRecording().

Here's a method that will work for all devices running iOS 9-11:

var isCoreMotionAuthorized: Bool {
    if #available(iOS 11.0, *) {
        return CMPedometer.authorizationStatus() == .authorized
    } else {
        // Fallback on earlier versions
        return CMSensorRecorder.isAuthorizedForRecording()
    }
}
Matthew Knippen
  • 1,048
  • 9
  • 22
1
[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.

This method will allow you to notify the user if the app isn't authorized to access Core Motion data. Simply create a CMPedometer instance called stepCounter and run the method above.

Michael Royzen
  • 463
  • 4
  • 12