网上找了那么多,基本都是来源于同一出处的,正所谓天下文章一大抄,你抄我来我抄你!
- 基于
Alamofire
的https单向认证,不需要导入证书
func authentication() {
let manager = Alamofire.SessionManager.default
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
}
- 如果项目使用了
Moya+Alamofire
的网络请求模式,如果网络请求不会走上面的认证方法,
那么有可能是Moya
的provider
默认的SessionManager
和上面方法中指定的manager
不一致,
需要重新为provider
指定manager
let provider = MoyaProvider<JMTAPIManager>(manager: Alamofire.SessionManager.default/*, plugins: [NetworkLoggerPlugin(verbose: true)]*/)