2013-10-06 117 views
4

我试图从AFNetworking 1.3迁移项目到AFNetworking 2.0。问题从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&param2=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]; 

} 

当客户端发送的格式不正确或不正确参数,服务器会返回一个400错误,包括JSON具有“descriptiveErrorMessage一个url “我在失败区读到。我使用这个“descriptiveErrorMessage”来确定URL的错误,并在适当的时候给用户留言。

的代码从AFNetworking 2.0项目看起来是这样的:

- (void)downloadJson:(id)sender 
{ 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myServer/api/call?param1=string1&param2=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?如果没有,任何人都可以提出一个更好的方法来做到这一点

在此先感谢您对此问题的任何帮助。

回答

4

我认为你可以尝试访问传递的operation参数的responseData属性给你的失败块。

不确定它将包含服务器发回的JSON数据,但所有信息都应该在那里。

希望它有帮助。

+0

谢谢@sergio,这工作。我错过了responseData属性。它来自NSData,但我将其序列化为JSON并能够从服务器检索消息。 – Paul

1

我找到了更好的解决方案。 我已经使用'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]); 
}];