【发布时间】:2017-10-11 21:50:51
【问题描述】:
在我的应用程序中,我有一个名为 User 的类,该类具有方法“login”,方法 login 只是对我的 API 的请求,但当我从控制器调用它时它不起作用。如果我将相同的代码复制到我的控制器中,它就可以工作。
这是我的方法:
func login () -> Void {
Alamofire.request("myUrl", method: .post , parameters: ["nick": "myNick", "pass" : "myPass"] , encoding: JSONEncoding.default, headers: nil).responseJSON{ response in
let status = response.response?.statusCode as! Int
switch status{
case 200:
let data = response.data
let utf8Text = String(data: data!, encoding: .utf8)
self.token = utf8Text
break
default:
break
}
}
}
这是我的控制器:
@IBAction func loginFunc(_ sender: Any) {
var usuario = User(nick:"myNick", pass:"myPass",token:nil)
usuario.login()
if usuario.token == nil{
let alert = UIAlertController(title: "¡Vaya!", message: "Ese nombre de usuario o esa contraseña son incorrectas", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Aceptar", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
print(usuario.token!)
}
它总是打印 nil 但服务器返回正确的令牌
【问题讨论】:
-
请求是异步的。这意味着
print在您得到响应之前运行。
标签: swift swift3 request response alamofire