iosswiftswiftui

Reacting to permission changes


CLLocationManager provides a way to react to authorization changes via the delegate's locationManagerDidChangeAuthorization method, but I've been unable to find the equivalent for other permission types. Namely, camera access or photo library access seems to not provide any way to react to the user going to setting and changing the authorization.

I guess I could dig into every method that I call and catch any error that's related to the feature's permission being denied but that is a really inferior approach. Is there a way to deterministically react to authorization changes in general for iOS development?


Solution

  • Each object, such as CLLocationManager, AVCaptureDevice, etc has different purposes. CLLocationManager has its own delegate to determine the authorization status, but that doesn't mean other objects need to.

    However, the common thing between these objects is that they have a way to get the current status:

    let videoPermission = AVCaptureDevice.authorizationStatus(for: .video)
    let audioPermission = AVAudioSession.sharedInstance().recordPermission
    ...
    

    The function / property can get called at any time. So, if that's the case, you want to determine whenever the user changes the permission in Setting, you can simply define a class and add some handlers whenever didBecomeActive or didFinishLaunchingWithOptions. Then indicate the behavior as you wish.

    final class PermissionHandler {
        enum PermissionType {
            case gallery
            case audioRecord
            case location
            ...
        }
    
        //There might be more states than below, but normally, I just announce these.
        enum Status {
            case undetermined
            case granted
            case denied
        }
    
        func getCurrentStatus(of type: PermissionType) -> Status {
            switch type {
                ...
            }
        }
    }