简体   繁体   中英

Swift: Listener for CMAuthorizationStatus changes

Is there a way to detect changes of the CMAuthorizationStatus ?

Currently it seems only possible to call eg CMMotionActivityManager.authorizationStatus() to get the status. However, I'm looking for a way to get a change event through a listener, if the state changes (or the user disabled/enabled the Motion & Fitness permission in the settings).

Since the status can also only be acquired through a function, I'm not able to set a KVO on the value.

Looking forward to your help.

I have been struggling with the same issue, I want to request the authorization once in the setup process so the user does not have to deal with the dialog later and then check for the permission every time the app gets launched.

For that I wrote the following code, first checking if the authorization was already set and otherwise initiating a call that should invoke the permission dialog. In this call I request the activity data from now to now, which theoretically doesn't make any sense, but returns one value or an error after the permission dialog was dismissed.

func checkMotionPermission(closure: @escaping (Bool) -> Void) {
    switch CMMotionActivityManager.authorizationStatus() {
    case .authorized:
        closure(true)
    case .notDetermined:
        let activityManager = CMMotionActivityManager()
        activityManager.queryActivityStarting(from: Date(), to: Date(), to: .main) { (activity, error) in
            let auth = CMPedometer.authorizationStatus()
            switch auth {
            case .authorized:
                closure(true)
            default:
                closure(false)
            }
        }
    default:
        closure(false)
    }
}

To get changes to the permission status you can call this method every time the application gets into foreground (in the AppDelegate), because that (while not being in your app) is the only time the user would be able to change the permission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM