項目開發(fā)過程中突然遇到了一個這個錯誤,一直搞了N長時間才找到問題。
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x9152780 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
一般認(rèn)為出現(xiàn)這個問題是服務(wù)器返回的數(shù)據(jù)不是標(biāo)準(zhǔn)的 JSON 格式,所以在代碼中加入如下代碼就能解決問題。
_manager = [AFHTTPSessionManager manager];
_manager.responseSerializer = [AFHTTPResponseSerializer serializer];
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/plain", nil];
一開始我加上這段代碼之后,有報下面的錯誤:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: not found (404)" UserInfo=0x7fb471f18110 {NSLocalizedDescription=Request failed: not found (404)...
于是就糾結(jié)了,并沒有改變請求相關(guān)的代碼,而且今天之前請求一直都是沒有問題的。那么問題會出在哪兒?(在這個問題上糾結(jié)了n個小時之后,發(fā)現(xiàn)最后那個 404)。
既然是 404 那就是服務(wù)器的問題,為什么之前運行正常突然會出現(xiàn)這個問題呢,刪除上面添加的代碼,那么程序會繼續(xù)報錯 NSCocoaErrorDomain Code=3840, 那么去 AF 的底層去找服務(wù)器一開始的返回值是什么,在
AFURLSessionManagerTaskDelegate 這個文件里面,
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
__block id responseObject = nil;
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
//Performance Improvement from #2672
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
self.mutableData = nil;
}
if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
}
// 添加下面這兩行代碼查看服務(wù)器的返回是什么,(猜測是服務(wù)器的問題,所以需要服務(wù)器端,添加 try...catch 捕獲異常,并返回給調(diào)用方)
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataStr);
到此就可以捕捉到問題所在。我遇到的問題是,我傳遞的參數(shù)里面有個字段的長度超過了數(shù)據(jù)庫里這個表默認(rèn)的長度,所以發(fā)生異常。具體問題具體分析吧。
記錄一下為了浪費的那 n 個小時。??????