在各種各樣的項(xiàng)目中會(huì)遇到各類(lèi)的開(kāi)發(fā)人員,代碼習(xí)慣,以及交互不同是很正常的.在近期一個(gè)項(xiàng)目中就遇到了當(dāng)后臺(tái)返回失敗信息的時(shí)候回直接在請(qǐng)求失敗中返回. ?但是很無(wú)奈的是打印出來(lái).無(wú)法獲取到后臺(tái)返回的信息. ?本來(lái)想找后臺(tái)好好干一番,說(shuō)他沒(méi)有返回.但安卓獲取到了.這就沒(méi)有辦法了.老老實(shí)實(shí)解決問(wèn)題:
廢話(huà)不多說(shuō)直接上代碼:
解決方案:
#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
以上代碼是直接可以使用的.創(chuàng)建一個(gè)類(lèi)然后直接拉入你的項(xiàng)目中
然后?修改響應(yīng)解析器數(shù)據(jù)類(lèi)型:
instance.responseSerializer = [HMFJSONResponseSerializerWithData serializer];
然后在調(diào)用失敗的里面打印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];
? ? ? ? }
? ? }
?有問(wèn)題可直接咨詢(xún)我+648731281 ?微信+17723566468 ?備注直接寫(xiě)簡(jiǎn)書(shū)