1
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.

WKWebViewを使ってローカルの自己署名証明書を使ってhttps接続をしようとして苦労した話

Last updated at Posted at 2019-09-19

(2019/10/06 SecTrustEvaluateでXcodeに文句を言われたので修正)

WKWebViewでローカルのサーバにhttps接続しようとしてもどうしても繋がらずまっしろい画面になってしまう

override func viewDidLoad() {
    super.viewDidLoad()

    let webConfiguration: WKWebViewConfiguration = WKWebViewConfiguration()
    self.webView = WKWebView(frame: CGRect.zero, configuration: webConfiguration)
    self.webView.uiDelegate = self
    self.webView.navigationDelegate = self
    self.view.addSubview(webView)

    let url: URL = URL(string: "https://localhost:8080")!
    let request: URLRequest = URLRequest(url: url)
    self.webView.load(request)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let width: CGFloat = self.view.bounds.size.width
    let height: CGFloat = self.view.bounds.size.height
    let frame: CGRect = CGRect(x:0, y:0, width: width, height: height)
    self.webView.frame = frame
}

信頼できない証明書を使っている場合はプロトコルWKNavigationDelegateの関数?didReceiveで失敗した認証に対して適切に処理を行う必要があるそう。

	func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
		// 認証の種類を確認してSSL/TLS認証以外はデフォルト処理
		if challenge.protectionSpace.authenticationMethod != NSURLAuthenticationMethodServerTrust { return completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) }
		// 証明書が取得できなかった場合はデフォルト処理
		guard let trust: SecTrust = challenge.protectionSpace.serverTrust else { return completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) }
		// とりあえず信頼してみる
		return completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: trust))
	}

どうしてもうまくいかず悩んでいたが、WKWebViewでロードするアドレスを https://localhost:8080 から https://127.0.0.1:8080 にしたら繋がるようになった
理由はよくわからない

1
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
1
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?