AFNetworking NSURLErrorDomain error -1012
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x758f120 {NSErrorFailingURLKey=https://api.com, NSErrorFailingURLStringK ey=https://api.com}
查找了apple文档错误码意思是 NSURLErrorUserCancelledA
查看错误码相关信息
因为我们的App采用的是https请求,很明显这个错误和ssl相关,google了-1012错误可查阅的资料很少,不过还是从stackoverflow找到了蛛丝马迹。
工程第三方包是用cocoapod管理,AFNetworking也是用pod install进来的,使AFNetworking支持https,参照之前写的文章AFNetworking支持https请求
pod install AFNetworking会报下面的错误
#ifndef __UTTYPE__ #if __IPHONE_OS_VERSION_MIN_REQUIRED #pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.") #else #pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.") #endif #endif
这个是缺少
#import <systemconfiguration /SystemConfiguration.h> #import <mobilecoreservices /MobileCoreServices.h>
其实我在工程pch文件已经添加了上面的import的,但是pods工程下面没自动添加,所以还是会包错,所以我自己手动去AFHTTPClient.h文件添加了,这样编译成功了也可以正常使用。我不知道你们在pod install后AFNetworking报错你们怎么解决,有更好办法的烦请下面留意告知。扯远了,还是回到-1012的错误问题上。其实问题很简单,让AFNetworking支持non self-signed cert 的https,你只需要#define_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
添加这句到pch文件,但是如果使用的是cocoapod管理的,你需要写一个AFHTTPRequestOperation的subclass,写入下面的代码:
@implementation SRHTTPRequestOperation - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstPr otectionSpace:(NSURLProtectionSpace *)protectionSpace { if ([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMetho dServerTrust]) { if ([self bypassSslCertValidation:protectionSpace]) return YES; else return [super connection:connection canAuthenticateAgainstPr otectionSpace:protectionSpace]; } return [super connection:connection canAuthenticateAgainstPr otectionSpace:protectionSpace]; } - (void)connection:(NSURLConnection *)connection didReceiveAuthentication Challenge:(NSURLAuthenticationChall enge *)challenge { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMetho dServerTrust]) { if ([self bypassSslCertValidation:challenge.protectionSpace]) { [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallen ge:challenge]; return; } else return [super connection:connection didReceiveAuthentication Challenge:challenge]; return; } } - (BOOL) bypassSslCertValidation:(NSURLProtectionSpace *) protectionSpace { return NO; } @end
我没按上面的方法去做。换成了以前的搞法,取消了AFNetworking用cooped管理,直接把AFNetworking的包拖到工程里,然后在pch里正常添加
```
#define AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES
#import <systemconfiguration /SystemConfiguration.h> #import <mobilecoreservices /MobileCoreServices.h>
```
经过测试-1012的错误没出现了。参考stackoverflow