查看原文:http://www.heyuan110.com/?p=1165
昨天App上传文件发起PUT和POST请求都随机会出现报-1012错误,具体错误信息:
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x758f120 {NSErrorFailingURLKey=https://api.com,NSErrorFailingURLStringKey=https://api.com}
查找了apple文档错误码意思是 NSURLErrorUserCancelledAuthentication =-1012
查看错误码相关信息
因为我们的App采用的是https请求,很明显这个错误和ssl相关,google了-1012错误可查阅的资料很少,不过还是从stackoverflow找到了蛛丝马迹。
工程第三方包是用cocoapod管理,AFNetworking也是用podinstall进来的,使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文件添加了,这样编译成功了也可以正常使用。我不知道你们在podinstall后AFNetworking报错你们怎么解决,有更好办法的烦请下面留意告知。扯远了,还是回到-1012的错误问题上。其实问题很简单,让AFNetworking支持nonself-signed cert 的https,你只需要#define_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
添加这句到pch文件,但是如果使用的是cocoapod管理的,你需要写一个AFHTTPRequestOperation的subclass,写入下面的代码:
@implementation SRHTTPRequestOperation- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{ if ([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) { if ([self bypassSslCertValidation:protectionSpace]) return YES; else return [super connection:connection canAuthenticateAgainstProtectionSpace:protectionSpace]; } return [super connection:connection canAuthenticateAgainstProtectionSpace:protectionSpace];}- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if ([self bypassSslCertValidation:challenge.protectionSpace]) { [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; return; } else return [super connection:connection didReceiveAuthenticationChallenge: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