AFNetworking 網路錯誤提示data轉換字串

來源:互聯網
上載者:User

標籤:ini   with   err   log   nfa   nsdata   val   erer   deb   

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);

AFNetworking 網路錯誤提示data轉換字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.