AFNetwoking返回error信息添加到body里

AFNetwoking对网络请求的封装已经非常好了,但我们对接口的处理变化比较大,有时候就会有一些不足的地方,比如说返回200以外的状态码以及解析返回的json,就会遇到一些问题。下面的一种方法可以解决以上问题,通过创建继承自AFJSONResponseSerializer的一个类来实现。

#import <AFNetworking/AFNetworking.h>
static NSString * const JSONResponseSerializerWithDataKey = @"body";
static NSString * const JSONResponseSerializerWithBodyKey = @"statusCode";
@interface YLJSONResponseSerializer : AFJSONResponseSerializer

@end

#import "YLJSONResponseSerializer.h"

@implementation YLJSONResponseSerializer
- (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;
} 


然后只需要把 AFJSONResponseSerializer 改成你建的类名就可以了,如代码

AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
mgr.responseSerializer = [YLJSONResponseSerializer serializer];


最后在failure里解析数据,举例如下,

// 失败后的处理
                                     NSDictionary *dict=error.userInfo;
                                     NSString *bodyString=dict[@"body"];
                                     NSData *jsonData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
                                     
                                     NSError *err;
                                     
                                     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                          
                                                                                         options:NSJSONReadingMutableContainers
                                                          
                                                                                           error:&err];
                                     [MBProgressHUD showMessage:dic[@"errorMsg"]];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值