所以我正在开发一个应用程序来登录我也在使用 alamofire 的东西。现在我想做的是当连接的响应代码为 200(成功)时让它进入一个新 View ,然后当响应代码为 204(失败)时进入不同的窗口我正在用 swift 3 写这个.
这是我当前的 IBAction
@IBAction func loginBtn(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
self.performSegue(withIdentifier: "login", sender: isvalid200())
self.dismiss(animated: true, completion: nil)
self.performSegue(withIdentifier: "error", sender: isinvalid())
现在我知道这不是应该如何完成的,但这是我的想法。另外,这是我的错误处理代码。
函数 isvalid200() {
Alamofire.request("https://myanimelist.net/api/account/verify_credentials.xml/\(user)/\(pass)")
.validate(statusCode: 200..<200) // if error is 200
.validate(contentType: ["application/json"])
}
func isinvalid() {
Alamofire.request("https://myanimelist.net/api/account/verify_credentials.xml/\(user)/\(pass)")
.validate(statusCode: 204..<204) // if error is 204
.validate(contentType: ["application/json"])
}
至于我得到的错误是这样的
MyAnime[7446:265163] > 的窗口不等于 的 View 的窗口!
(没有 self.dimiss 但有了它,它确实有效,但它不会根据响应代码 I.E 200 或 204 停留在特定窗口。
任何帮助都会很棒!
最佳答案
试试像这样打开 statusCode 的东西
@IBAction func loginBtn(_ sender: Any) {
Alamofire.request("https://myanimelist.net/api/account/verify_credentials.xml/\(user)/\(pass)").responseJSON { [weak self] response in
guard let strongSelf = self, let resp = response.response else { return }
switch resp.statusCode {
case 200:
DispatchQueue.main.async {
strongSelf.performSegue(withIdentifier: "login", sender: strongSelf)
}
case 204:
DispatchQueue.main.async {
strongSelf.performSegue(withIdentifier: "error", sender: strongSelf)
}
default:
//Some other status code
}
}
}
为了对发生的事情给出一些解释,让我们逐步分解它:
- 用户在输入用户名/密码后按下登录按钮
- 您发出网络请求以验证凭据
- 收到响应后,您可以根据状态码判断这是否是有效用户
- 此时,您只需要执行必要的 segue 以转换到下一个 View Controller 。如果您想返回呈现 View Controller ,您只会调用 dismiss。
关于swift - 如果来自 Alamofire 请求的响应是否为 200,我将如何更改后续 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41214236/