iosswiftmpmedialibrary

How to wait for MPMediaLibrary requestAuthorization response


Im checking the response the user gives when prompted for accessing the media-library. I want to know how can i wait for the response of the user before continuing

static func getAuthrization(completionHandler:@escaping (Bool) -> Void)  {
        var authStatus:Bool=false;
        let status = MPMediaLibrary.authorizationStatus()
        if(status == MPMediaLibraryAuthorizationStatus.authorized){
            authStatus = true
        }else{
            MPMediaLibrary.requestAuthorization() { status in
                if status == .authorized {
                    authStatus = true
                }else{
                    print("Auth not granted")
                    authStatus = false
                }
            }
        }
        completionHandler(authStatus)
    }

This is the function that i use to get user authentication.

func setSongs(){
        print("called from set songs")
        songQuery.getAuthrization { (status) in
            print(status)
        }
    }

And this is the function that i use to call that function

right now the function gets executed and finished before the user response from the system permission prompt. What i want is the for the code to await like in js or dart before executing and then get the response.

Any help is appreciated


Solution

  • Call completionHandler as below,

    static func getAuthrization(completionHandler:@escaping (Bool) -> Void)  {
            if MPMediaLibrary.authorizationStatus() == .authorized {
                completionHandler(true)
            } else {
                MPMediaLibrary.requestAuthorization() { completionHandler($0 == .authorized) }
            }
        }