4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デバッグ時の自己証明書(オレオレ証明書)の回避方法

Last updated at Posted at 2018-02-03

概要

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文で囲んでやる必要があります。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?