AFN在進行網絡交互時,有時候會碰到返回502、500、404的時候。后台的總需要你配合他查出問題所在。但是AFN在返回數據序列化時解析錯誤只會轉成NSData類型的數據,如果直接扔給后台Data的數據顯然有點不靠譜。所以可以在AFURLResponseSerialization.m中加上對data轉成string的方法。方法如下:
在AFURLResponseSerialization.m中找到 “AFNetworkingOperationFailingURLResponseDataErrorKey”在其下方加上
#ifdef DEBUG
NSString * const AFNetworkingOperationFailingURLResponseStringErrorKey = @"com.alamofire.serialization.response.error.string";
#endif
ps:主要是在debug狀態下需要調試,所以加上環境的判斷防止錯誤。
第一:
然后分別在- (BOOL)validateResponse:(NSHTTPURLResponse )response data:(NSData )data error:(NSError * __autoreleasing *)error 方法中在判斷data的代碼中有兩處需要替換:
if (data) {
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
替換成、
if (data) {
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
#ifdef DEBUG
mutableUserInfo[AFNetworkingOperationFailingURLResponseStringErrorKey] = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
#endif
}
之后當你碰到網絡錯誤時。AFN會把錯誤輸出,可以搜索console中搜索com.alamofire.serialization.response.error.string:對應的就是data轉成的字符串。
第二:
NSError *underError = error.userInfo[@"NSUnderlyingError"];
NSData *data=underError.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
