gpt4 book ai didi

ios - 从 AFNetworking 1.3 迁移到 AFNetworking 2.0 的问题

转载 作者:可可西里 更新时间:2023-11-01 05:36:01 27 4
gpt4 key购买 nike

我正在尝试将一个项目从 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,我在失败 block 中读取了它。我使用这个“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 获取响应 header ,但这是我所能得到的,也许我遗漏了一些东西。

有没有办法在失败 block 中获取 JSON?如果没有,有人可以建议更好的方法吗?

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

最佳答案

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

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

希望对您有所帮助。

关于ios - 从 AFNetworking 1.3 迁移到 AFNetworking 2.0 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19210835/

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