Alamofireasynchronous调用

我有一个简单的问题。 我正在连接到我的RESTful服务器并尝试连接。 我得到了一个响应,一切工作完美,但是当我尝试调用一个函数来设置一个variables,它只是不叫它。

码:

// // LoginClass.swift // LoginApp // // Created by Tarek Adel on 12/3/16. // Copyright © 2016 Tarek Adel. All rights reserved. // import Foundation import Alamofire; import UIKit; class LoginClass { var result: Bool = false; var username: String var password: String init(username: String, password:String) { self.username = username; self.password = password; } func login() -> Void { let data = [ "grant_type" : "password", "username" : self.username, "password" : self.password, "client_secret":"xxxxxx", "client_id":"xxxxxx", "scope": "" ] Alamofire.request("http://localhost:8000/oauth/token", method: .post, parameters: data) .responseJSON { response in //to get status code if let status = response.response?.statusCode { switch(status){ case 200: self.loginSuccess(); default: print("error with response status: \(status)") } } //to get JSON return value if let result = response.result.value { let JSON = result as! NSDictionary print(JSON) } } } func loginSuccess() { self.result = true; } } 

这是我检查self.result

 @IBAction func loginButton(_ sender: UIButton) { let username = usernameTextField.text!; let password = passwordTextField.text!; let loginClass = LoginClass(username: username, password:password) loginClass.login() if(loginClass.result == true) { resultLabel.text = "Correct!" } else { resultLabel.text = "Wrong Credentials" } } 

您需要使用您的login方法使用完成处理程序,因为它正在进行asynchronous调用,所以使用您的login方法创build一个completionHandler ,然后在该completionHandler内部执行条件。

 func login(completionHandler: (_ result: Bool) -> ()) { let data = [ "grant_type" : "password", "username" : self.username, "password" : self.password, "client_secret":"xxxxxx", "client_id":"xxxxxx", "scope": "" ] Alamofire.request("http://localhost:8000/oauth/token", method: .post, parameters: data) .responseJSON { response in //to get status code if let status = response.response?.statusCode { switch(status){ case 200: //to get JSON return value if let result = response.result.value { let JSON = result as! NSDictionary print(JSON) } completionHandler(true) default: print("error with response status: \(status)") completionHandler(false) } } } } 

现在调用这个login方法。

 self.login { (result) in if(result) { resultLabel.text = "Correct!" } else{ resultLabel.text = "Wrong Credentials" } } 

注意:如果你想要JSON响应,然后使用两个参数Bool和Dictionary完成处理程序,并传递JSON。