Help how I can implementing closure in authManger.Login wapper function to Alamofire authenticate?

I have created this static function Login to wrap Alamofire authenticate function. I have one problem how to implementing closure with Alamofire authenticate and how to call it in action asynchronous.

class AutheManager{

let username:String = "user"
let password:String = "password"
var manager: Session!

static func Login(username:String, password:String, completion: @escaping (_ success: Bool, _ response: DataResponse<Data?>?) -> ()) {

    var response:DataResponse<Data?>?
    
    AF.request("https://httpbin.org/basic-auth/\(username)/\(password)")
        .authenticate(username: username, password: password)
        .response { resp in
            response = resp
            completion(true,response)
    }
    
    if(response?.response?.statusCode == 200)
    {
        completion(true, response)
    }
    else {
        completion(false, nil)
    }
}
}
//code from action outlet 
@IBAction func loginAction(sender: UIButton)
{
    AutheManager.Login(username: newAccountName, password: newPassword) { (success, response) in
        if (success  == true)
        {
            // rest of code 
        }
        else 
        {

        }
    }
}

I don’t know much about AlamoFire, so I am just assuming that your AF.request(…) call is correct.

It seems to me based on what you have that the the call should look like this:

AF.request("https://httpbin.org/basic-auth/\(username)/\(password)")
    .authenticate(username: username, password: password)
    .response { resp in
        response = resp
        if(response?.response?.statusCode == 200)
        {
              completion(true, response)
        }
        else {
              completion(false, nil)
        }
    }

That is, put your conditional test inside the .response closure, so that it checks the statusCode and calls the passed in completion accordingly.

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.