Как сделать обертку асинхронной функции входа в систему вокруг метода Alamofire.authenticate в Swift? - PullRequest
0 голосов
/ 26 декабря 2018

У меня есть вызов этого класса-оболочки AutheManager.У него один статический вызов функции. Войдите в обертку вокруг метода Alamofire.authenticate. Я хочу спросить, как я могу реализовать асинхронное ожидание ответа HTTP для завершения перехода к следующей логике

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

        var response =

        AF.request("https://httpbin.org/basic-auth/\(username)/\(password)")
            .authenticate(username: username, password: password)
            .response { resp in
                response = resp
        }
        return response
    }  
}

@IBAction func loginAction(sender: UIButton)
    {
        // Check that text has been entered into both the username and password fields.
        guard let newAccountName = emailTextField.text,
            let newPassword = passwordTextField.text,
            !newAccountName.isEmpty,
            !newPassword.isEmpty else {
                showLoginFailedAlert()
                return
        }


        //get response from AutheManager
        response = AutheManager.Login(username: newAccountName, password: newPassword)

    }   

1 Ответ

0 голосов
/ 26 декабря 2018

Добавить замыкание в конце метода AutheManager.Login

AutheManager.Login(username: String, password: String, completion: @escaping (_ success: Bool, response: [String: Any]?) -> ()) {

    ...

    //call once you get response, for success
    completion(true, response)

    //for failure
    completion(false, nil)
    ...

}

Теперь вызовите этот метод:

AutheManager.Login(username: newAccountName, password: newPassword) { (success, response) in

   guard success, let response = response else { //show message }

   print(response)

   ///move you rest of the code/logic here

}
...