Joe Masilotti
Joe Masilotti

Reputation: 17018

Determine authorization status of Core Motion Services (eg. M7) before prompting user?

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?

Upvotes: 2

Views: 3692

Answers (2)

Matthew Knippen
Matthew Knippen

Reputation: 1058

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()
    }
}

Upvotes: 4

Michael Royzen
Michael Royzen

Reputation: 463

[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.

Upvotes: 1

Related Questions