我正在尝试将一个项目从AFNetworking 1.3迁移到AFNetworking 2.0。
在AFNetworking 1.3项目中,我有以下代码:
- (void) downloadJson:(id)sender
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myServer/api/call?param1=string1¶m2=string2"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// handle success
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"%ld", (long)[response statusCode]);
NSDictionary *data = JSON;
NSString *errorMsg = [data objectForKey:@"descriptiveErrorMessage"];
// handle failure
}];
[operation start];
}
当客户端发送一个未正确格式化或参数错误的url时,服务器将返回一个400个错误,并包含带有“descriptiveErrorMessage”的JSON,我在failure块中读取了它。我使用这个“descriptiveErrorMessage”来确定url有什么问题,并在适当的情况下向用户发送消息。
AFNetworking 2.0项目的代码如下所示:
- (void)downloadJson:(id)sender
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myServer/api/call?param1=string1¶m2=string2"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// handle success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// any way to get the JSON on a 400 error?
}];
[operation start];
}
在JSON2.0项目中,我看不到让AFNetworking读取服务器发送的“descriptiveErrorMessage”的任何方法。我可以在操作中从NSHTTPURLResponse获得响应头,但这是我所能得到的,也许我遗漏了什么。
有办法在failure块中获取JSON吗?如果没有人能提出更好的方法来做这件事吗?
提前感谢您对这个问题的任何帮助。
发布于 2013-10-06 16:51:38
我认为您可以尝试访问传递给失败块的responseData
参数的operation
属性。
不确定它是否包含您的服务器返回的JSON数据,但是所有信息都应该在那里。
希望能帮上忙。
发布于 2013-12-03 10:03:23
我找到了更好的解决办法。我用过“AFHTTPRequestOperationManager”
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:@"http://localhost:3005/jsondata" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Result: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", [error localizedDescription]);
}];
https://stackoverflow.com/questions/19210835
复制相似问题