解決使用AFNetwoking請(qǐng)求失敗的時(shí)候如何獲取error body

在各種各樣的項(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ū)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容