gpt4 book ai didi

ios - Alamofire 中的错误处理

转载 作者:IT王子 更新时间:2023-10-29 05:18:43 26 4
gpt4 key购买 nike

我在 AngularJS Controller 中有 HTTP 代码:

$http.post('/api/users/authenticate', {email: $scope.email, password: $scope.password})
.success(function (data, status, headers, config) {
authService.login($scope.email);
$state.go('home');
})
.error(function (data, status, headers, config) {
$scope.errorMessages = data;
$scope.password = "";
});

在成功的情况下,服务器将以用户的 JSON 表示形式进行响应。在错误情况下,服务器将使用一个简单的字符串作为响应,例如 User not found 可以通过 data 参数访问。

我无法弄清楚如何在 Alamofire 中执行类似的操作。这是我现在拥有的:

@IBAction func LoginPressed(sender: AnyObject) {
let params: Dictionary<String,AnyObject> = ["email": emailField.text, "password": passwordField.text]

Alamofire.request(.POST, "http://localhost:3000/api/users/authenticate", parameters: params)
.responseJSON {(request, response, data, error) in
if error == nil {
dispatch_async(dispatch_get_main_queue(), {
let welcome = self.storyboard?.instantiateViewControllerWithIdentifier("login") as UINavigationController;

self.presentViewController(welcome, animated: true, completion: nil);
})
}
else{
dispatch_async(dispatch_get_main_queue(), {
// I want to set the error label to the simple message which I know the server will return
self.errorLabel.text = "something went wrong"
});
}
}
}

我也不知道我是否正确处理了非错误情况,也希望能提供相关意见。

最佳答案

您走在正确的轨道上,但您将在当前实现过程中遇到一些关键问题。有一些低级别的 Alamofire 东西会让你绊倒,我想帮助你。这是您的代码示例的替代版本,它会更有效。

@IBAction func loginPressed(sender: AnyObject) {
let params: [String: AnyObject] = ["email": emailField.text, "password": passwordField.text]

let request = Alamofire.request(.POST, "http://localhost:3000/api/users/authenticate", parameters: params)
request.validate()
request.response { [weak self] request, response, data, error in
if let strongSelf = self {
let data = data as? NSData

if data == nil {
println("Why didn't I get any data back?")
strongSelf.errorLabel.text = "something went wrong"
return
} else if let error = error {
let resultText = NSString(data: data!, encoding: NSUTF8StringEncoding)
println(resultText)
strongSelf.errorLabel.text = "something went wrong"
return
}

var serializationError: NSError?

if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments, error: &serializationError) {
println("JSON: \(json)")
let welcome = self.storyboard?.instantiateViewControllerWithIdentifier("login") as UINavigationController
self.presentViewController(welcome, animated: true, completion: nil)
} else {
println("Failed to serialize json: \(serializationError)")
}
}
}
}

验证

首先,请求中的validate 函数将验证以下内容:

  • HTTPStatusCode - 必须为 200...299
  • Content-Type - 响应中的这个 header 必须与原始请求中的 Accept header 匹配

您可以在 README 中找到有关 Alamofire 验证的更多信息.

弱化/强化

确保你的闭包弱化 self 并强化 self ,以确保你最终不会创建保留循环。

分派(dispatch)到主队列

您的调度调用返回主队列是没有必要的。 Alamofire 保证 responseresponseJSON 序列化程序中的完成处理程序已经在主队列上调用。如果您愿意,您实际上可以提供自己的调度队列来运行序列化程序,但是您或我的解决方案目前都没有这样做,因此完全没有必要对主队列进行调度调用。

响应序列化器

在您的特定情况下,您实际上并不想使用 responseJSON 序列化程序。如果这样做,如果您没有通过验证,您将不会最终获得任何数据。原因是来自 JSON 序列化的响应将作为 AnyObject 返回。如果序列化失败,AnyObject 将为 nil,您将无法读取数据。

相反,使用response 序列化程序并尝试使用NSJSONSerialization 手动解析数据。如果失败,那么您可以依靠好的 ole NSString(data:encoding:) 方法来打印数据。

希望这有助于阐明一些相当复杂的被绊倒的方法。

关于ios - Alamofire 中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024703/

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