AFN 控制字符報錯(沒法解析)

報錯:服務器

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 2884.) UserInfo=0x79fa60b0 {NSDebugDescription=Unescaped control character around character 2884.}post

緣由在於出現特殊字符是AFNetworking沒法解析的,會直接報錯,那麼當你在發post請求時,返回結果會直接進如fail代碼塊,其實在fail中用operation的nsstring能夠直接輸出接收到的數據,是string形,能夠清楚的看到服務器端數據有哪些含有特殊字符,可是有一些字符是很差看到的,好比「TAB」(製表)鍵打出的那種四個空格,項目中用戶有時候很經常使用到tab鍵,最好的方法是在AFNetworking源碼中添加字符過濾功能spa

處理辦法:找到AFNetworking包中AFURLResponseSerialization.m文件,大概在第256行的 if (responseString && ![responseStringisEqualToString:@" "])(此時已將data轉化爲responseString形)條件下面添加以下過濾方法:blog

NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];  
                NSRange range = [responseString rangeOfCharacterFromSet:controlChars];  
                if (range.location != NSNotFound)  
                {  
                    NSMutableString *mutable = [NSMutableString stringWithString:responseString];  
                    while (range.location != NSNotFound)  
                    {  
                        [mutable deleteCharactersInRange:range];  
                        range = [mutable rangeOfCharacterFromSet:controlChars];  
                    }  
                    responseString = mutable;  
                }  

  OK,再試一下,應該不會在報錯了。ip

相關文章
相關標籤/搜索