4

我正在尝试将项目从 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];

}

当客户端发送的 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&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

2 回答 2

4

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

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

希望能帮助到你。

于 2013-10-06T16:51:38.240 回答
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]);
}];
于 2013-12-03T10:03:23.020 回答