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];
// 失败后的处理
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"]];