AFNetworking如何获取完整的error body

来源:互联网 发布:青岛网络电视户外运动 编辑:程序博客网 时间:2024/05/16 06:58

      发现很多人都遇到了同样的问题,当我们使用AFNetwoking请求失败的时候,我们想要获取一下失败的信息,系统只返回给我们一个status code,却不告诉我们具体原因。


我在这里简单的说一下应该如何进行操作才能得到完整的错误信息。

新建一个类名为

HMFJSONResponseSerializerWithData


我们在

HMFJSONResponseSerializerWithData.h中写上

#import "AFURLResponseSerialization.h"/// NSError userInfo keys that will contain response datastatic NSString * const JSONResponseSerializerWithDataKey = @"body";static NSString * const JSONResponseSerializerWithBodyKey = @"statusCode";@interface HMFJSONResponseSerializerWithData : AFJSONResponseSerializer@end

HMFJSONResponseSerializerWithData.m中写上

#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

然后在需要使用该方法的文件中先引用这个类

在做请求之前添加上如下代码

NSString * url = [NSStringstringWithFormat:@"%@agent/user",BaseUrl];

    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager

                                               alloc] init];

    

    manager.responseSerializer = [HMFJSONResponseSerializerWithDataserializer];

    








注* 我是根据一篇国外的文章写的。

0 0
原创粉丝点击