美文网首页
AFNetworking Post 请求报错 Error Dom

AFNetworking Post 请求报错 Error Dom

作者: z_hy | 来源:发表于2018-12-04 13:31 被阅读12次

项目开发过程中突然遇到了一个这个错误,一直搞了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.}

一般认为出现这个问题是服务器返回的数据不是标准的 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)...

于是就纠结了,并没有改变请求相关的代码,而且今天之前请求一直都是没有问题的。那么问题会出在哪儿?(在这个问题上纠结了n个小时之后,发现最后那个 404)。
既然是 404 那就是服务器的问题,为什么之前运行正常突然会出现这个问题呢,删除上面添加的代码,那么程序会继续报错 NSCocoaErrorDomain Code=3840, 那么去 AF 的底层去找服务器一开始的返回值是什么,在
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;
    }
    // 添加下面这两行代码查看服务器的返回是什么,(猜测是服务器的问题,所以需要服务器端,添加 try...catch 捕获异常,并返回给调用方)
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", dataStr);

到此就可以捕捉到问题所在。我遇到的问题是,我传递的参数里面有个字段的长度超过了数据库里这个表默认的长度,所以发生异常。具体问题具体分析吧。

记录一下为了浪费的那 n 个小时。🤣😂😂

相关文章

网友评论

      本文标题:AFNetworking Post 请求报错 Error Dom

      本文链接:https://www.haomeiwen.com/subject/qlymcqtx.html