AFNetworking和Alamofire设置跳过https(SSL)验证

我们服务器用的是https但是没用证书,客户端不验证,在ios11之前是不用做处理的,在下载了ios11之后发现请求失败了,就是证书验证失败,想必是这次版本更新的一点小变化吧。

现在项目用的是AFNetworking 3.0.2版本报错

Error Domain=NSURLErrorDomain Code=-999 “已取消”


然后换了swift的Alamofire请求报错是

Domain=NSURLErrorDomain Code=-1202 “The certificate for this server is invalid. You might be connecting to a server that is pretending to be “api.domain.cn” which could put your confidential information at risk.” UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9807….

总之就是证书的问题了,我们服务器是没有验证证书的 所以需要前端这边声明跳过验证的

网上查了下找到了如下解决办法

OC的代码如下

1
2
3
4
5
6
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
// allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
// 如果是需要验证自建证书,需要设置为YES
securityPolicy.allowInvalidCertificates = YES;
[securityPolicy setValidatesDomainName:NO];
[manger setSecurityPolicy:securityPolicy];

Swift用Alamofire解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
public func defaultAlamofireManager() -> Manager {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
let policies: [String: ServerTrustPolicy] = [
"api.domian.cn": .disableEvaluation
]
let manager = Alamofire.SessionManager(configuration: configuration,serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
manager.startRequestsImmediately = false
return manager
}