查了很多网上的文章,对moya的https证书校验基本都是略,要么就是16/17年的代码,但是运行的时候找到证书,转data格式的时候报错,崩溃;
Alamofire 5.0之后,对于ssl证书认证相关代码有修改。
pod 'Moya/RxSwift', '~> 14.0'
不费话,下面直接看代码吧,希望对你们有帮助;
//MARK: 设置ssl
let session : Session = {
//证书数据
func certificate() -> SecCertificate? {
let filePath = Bundle.main.path(forResource: "存在Xcode中证书的文件名", ofType: "cer")
if filePath == nil {
return nil
}
let data = try! Data(contentsOf: URL(fileURLWithPath: filePath ?? ""))
let certificate = SecCertificateCreateWithData(nil, data as CFData)!
return certificate
}
guard let certificate = certificate() else {
return Session()
}
let trusPolicy = PinnedCertificatesTrustEvaluator(certificates: [certificate], acceptSelfSignedCertificates: false, performDefaultValidation: true, validateHost: true)
let trustManager = ServerTrustManager(evaluators: ["你证书的域名,比如www.baidu.com或者baidu.com" : trusPolicy])
let configuration = URLSessionConfiguration.af.default
return Session(configuration: configuration, serverTrustManager: trustManager)
}()
//把session当参数传进去就行了
let kProvider = MoyaProvider<HXNetworkAPI>(endpointClosure: myEndpointClosure, requestClosure: requestClosure, session: session, plugins: [networkActivityPlugin], trackInflights: false)