最近在做文件上传功能的时候遇到了一些问题,有关AFNetworking失败的一些错误码,这里整理一下,以免以后再踩坑:

【1】错误码-999,错误信息具体如下:

Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://test.com/xxxxxx, NSLocalizedDescription=cancelled, NSErrorFailingURLKey=https://test.com/xxxxxx}

 原因和代码如下:

AFHTTPSessionManager *manage = [[AFHTTPSessionManager alloc] init];;
        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];//报错时使用的证书校验方式为AFSSLPinningModeCertificate,但此时访问的url证书校验并未成功,所以更改为AFSSLPinningModeNone即可
        policy.validatesDomainName = YES;
        manage.securityPolicy = policy;

 

【2】错误码-1011,404,错误信息如下:

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: not found (404)" UserInfo={NSLocalizedDescription=Request failed: not found (404), NSErrorFailingURLKey=https://test.com/xxxxxx, com.alamofire.serialization.response.error.data=<>, com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x60400c03ee80> { URL: https://test.com/xxxxxx } { Status Code: 404, Headers {
	Content-Type : [
	application/octet-stream
],
	Content-Length : [
	0
],
	Server : [
	nginx
],
	Date : [
	Wed, 16 May 2018 10:22:10 GMT
]
} }}

看到这个错误码请不要怀疑,这个就是你要访问的url访问不到所导致的,请检查你的URL

 

【3】错误码3840,400,错误信息如下

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x6000058569e0 {Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={NSLocalizedDescription=Request failed: bad request (400), NSErrorFailingURLKey=https://test.com/xxxxxx , com.alamofire.serialization.response.error.data=<3c68746d 6c3e0a3c 68656164 3e0a3c6d 65746120 68747470 2d657175 69763d22 436f6e74 656e742d 54797065 2220636f 6e74656e 743d2274 6578742f 68746d6c 3b206368 61727365 743d4953 20343030 3c2f6832 3e0a3c70 3e50726f 626c656d 20616363 65737369 6e67202f 772f6578 7465726e 616c2f75 706c6f61 6466696c 652e2052 6561736f 6e3a0a3c 7072653e 20202020 52657175 69726564 204d756c 74697061 72744669 6c652070 6172616d 65746572 20276669 6c652720 6973206e 6f742070 72657365 6e743c2f 7072653e 3c2f703e 3c687220 2f3e3c69 3e3c736d 616c6c3e 506f7765 72656420 6279204a 65747479 3a2f2f3c 2f736d61 6c6c3e3c 2f693e3c 62722f3e 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 0a3c6272 2f3e2020 >, com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x60400c62b5a0> { URL: https://test.com/xxxxxx  } { Status Code: 400, Headers {
	Date : [
	Tue, 15 May 2018 01:22:33 GMT
],
	Content-Type : [
	text/html;charset=ISO-8859-1
],
	Content-Length : [
	1476
],
	Cache-Control : [
	must-revalidate,no-cache,no-store
],
	Server : [
	nginx
]
} }}}}

 这是是你填充数据的问题,请检查你的数据设置是否正确,刚出现这个问题的时候看描述以为是服务器端返回的格式不是约定的json所以不能解析造成的,但是请服务端同事核对了返回数据确实是json,然后怀疑以下返回数据可解析格式未设置@"text/json",检查后发现也设置了

AFHTTPSessionManager *manage = [[AFHTTPSessionManager alloc] init];
        manage.responseSerializer = [[AFJSONResponseSerializer alloc] init];
        manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"application/x-www-form-urlencoded", @"multipart/form-data", @"text/plain", @"image/jpeg", @"image/png", @"application/octet-stream",nil];

 后来经过进一步的查阅资料发现,因为是文件上传,所以直接使用了NSData拼接导致的问题,错误代码示例如下:

NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMapped error:nil];
    [[AFHTTPSessionManager shareInstance] POST:URL_KANO_UPLOADFILE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:data name:@"file"];//此处不可这样拼接
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)    {
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
    }];

 而应该使用对应的mimeType类型做区分拼接

[[AFHTTPSessionManager shareInstance] POST:URL_KANO_UPLOADFILE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSError *error;
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        [formData appendPartWithFileURL:fileURL
                                   name:@"file"
                               fileName:fileName
                               mimeType:@"image/jpeg"
                                  error:&error];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

 具体的mimeType类型此处不再赘述,请读者自行查阅学习。

 【4】错误码-1022,错误信息如下:

 Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x60400025a640 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=https://test.com/xxxx, NSErrorFailingURLKey=https://test.com/xxxx, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}

出错原因:iOS9以后,苹果把原http协议改成了https协议,所以不能直接在http协议下GET/POST

解决办法有两种:

1.直接编辑工程文件下的Info.plist文件,加入以下代码

<key>NSAppTransportSecurity</key>  
  <dict>  
    <key>NSAllowsArbitraryLoads</key>
    <true/>  
  </dict>

2.在Xcode里选中info.plist,点击右边的information Property List 后边的加号,写入App Transport Security Settings然后回车,先点击左侧展开箭头,再点右侧加号,Allow Arbitrary Loads 已经自动生成,直接回车,然后把默认值改为YES即可。其实这种方法等同于方法1.

 

【5】错误码-1016,错误信息如下:

Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain" UserInfo={NSLocalizedDescription=Request failed: unacceptable content-type: text/plain, NSErrorFailingURLKey=https://test.com/xxxx, com.alamofire.serialization.response.error.data=<7b227374 61676522 3a226777 222c2263 6f646522 3a323030 3035312c 226d6573 73616765 223a22e7 adbee590 8de99499 e8afaf22 2c227375 63636573 73223a66 616c7365 7d>, com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x600000220640> { URL: https://test.com/xxxx } { Status Code: 200, Headers {
    Connection =     (
        "keep-alive"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Type" =     (
        "text/plain; charset=utf-8"
    );
    Date =     (
        "Fri, 18 May 2018 07:14:25 GMT"
    );
    Server =     (
        nginx
    );
    "Transfer-Encoding" =     (
        Identity
    );
    Vary =     (
        "Accept-Encoding"
    );
    "X-Content-Type-Options" =     (
        nosniff
    );
    "X-XSS-Protection" =     (
        1
    );
} }}

因为未设置AFHTTPSessionManager的requestSerializer的可接受文件类型,所以造成text/plain类型数据不可接受导致以上问题,进行下列设置即可:

manager.responseSerializer = [[AFJSONResponseSerializer alloc] init];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"application/x-www-form-urlencoded", @"multipart/form-data", @"text/plain", @"image/jpeg", @"image/png", @"application/octet-stream",  nil];

 

posted on 2018-05-16 19:59  fatal-奚山遇白  阅读(1711)  评论(0编辑  收藏  举报