gpt4 book ai didi

swift - Alamofire 请求在方法内不起作用,但相同的请求在 Controller 内起作用 | swift 3.0

转载 作者:行者123 更新时间:2023-11-30 12:05:47 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个名为 User 的类,该类具有“登录”方法,该方法登录只是对我的 API 的请求,但当我从 Controller 调用它时它不起作用。如果我将相同的代码复制到我的 Controller 中,它就可以工作。

这是我的方法:

    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
}

}

}

这是我的 Controller :

    @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,但服务器返回正确的 token

最佳答案

您必须使用完成 block :

func login (completion : ()->()) {
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
}
completion()
}
}

@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!)
}
}

关于swift - Alamofire 请求在方法内不起作用,但相同的请求在 Controller 内起作用 | swift 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46698108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com