概要
iOSアプリをStaging環境でテストする場合などに、サーバ側の証明書が自己署名証明書になっていると通信エラーが生じる場合があります。その場合、下記のようにiOSのプライベートAPIを利用することで証明書エラーを回避する方法があります。
自己署名証明書を回避する
# if DEBUG
extension NSURLRequest {
static func allowsAnyHTTPCertificate(forHost host: String) -> Bool {
return true
}
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let serverTrust = challenge.protectionSpace.serverTrust {
let credential = URLCredential(trust: serverTrust)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
}
}
}
# endif
注意点
プライベートAPIを使用したコードはリリースビルドに含むことはできない(ipaアップロード時に弾かれる)ので、DEBUGやSTAGING用のSchemeを用意して上記のようにif文で囲んでやる必要があります。