发布于 3年前

解决使用AFNetwoking请求失败的时候如何获取error body

在各种各样的项目中会遇到各类的开发人员,代码习惯,以及交互不同是很正常的.在近期一个项目中就遇到了当后台返回失败信息的时候回直接在请求失败中返回. 但是很无奈的是打印出来.无法获取到后台返回的信息. 本来想找后台好好干一番,说他没有返回.但安卓获取到了.这就没有办法了.老老实实解决问题:

废话不多说直接上代码:

解决方案:

#import "AFURLResponseSerialization.h"

/// NSError userInfo keys that will contain response data

static NSString * const JSONResponseSerializerWithDataKey = @"body";

static NSString * const JSONResponseSerializerWithBodyKey = @"statusCode";

@interface HMFJSONResponseSerializerWithData : AFJSONResponseSerializer

@end

#import "HMFJSONResponseSerializerWithData.h"

@implementation HMFJSONResponseSerializerWithData

- (id)responseObjectForResponse:(NSURLResponse *)response

data:(NSData *)data

error:(NSError *__autoreleasing *)error

{

id JSONObject = [super responseObjectForResponse:response data:data error:error]; // may mutate error

if (*error != nil) {

NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy];

[userInfo setValue:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] forKey:JSONResponseSerializerWithDataKey];

[userInfo setValue:[response valueForKey:JSONResponseSerializerWithBodyKey] forKey:JSONResponseSerializerWithBodyKey];

NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo];

(*error) = newError;

}

return JSONObject;

}

@end

以上代码是直接可以使用的.创建一个类然后直接拉入你的项目中

然后 修改响应解析器数据类型:

instance.responseSerializer = [HMFJSONResponseSerializerWithData serializer];

然后在调用失败的里面打印error 你就可以获取到body. 完美解决

failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@"error=%@",error);

[MBProgressHUD hideHUDForView:self.view animated:YES];

NSDictionary *dict=error.userInfo;

NSString *bodyString=dict[@"body"];

if (bodyString.length!=0) {

bodyString=[bodyString substringFromIndexSafe:1];

bodyString=[bodyString substringToIndexSafe:bodyString.length-1];

[MBProgressHUD showMsg:bodyString];

}

}

相关文章

©2020 edoou.com   京ICP备16001874号-3