我正在尝试将项目从 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,我在失败块中读取了该信息。我使用这个“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];
}
在 AFNetworking 2.0 项目中,我看不到任何让 JSON 读取服务器发送的“descriptiveErrorMessage”的方法。我可以在操作中从 NSHTTPURLResponse 获取响应标头,但据我所知,也许我遗漏了一些东西。
有没有办法在失败块中获取 JSON?如果没有,有人可以提出更好的方法吗?
提前感谢您对此问题的任何帮助。