1
0

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 1 year has passed since last update.

【Swift】WKNavigationDelegateについて

Posted at

WKNavigationDelegateとは

webViewのナビゲーションイベントをハンドリングするためのプロトコルです。

実装方法

class ViewController: UIViewController, WKNavigationDelegate {
    @IBOutlet weak var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.navigationDelegate = self
        
        if let url = URL(string: "https://example.com") {
            webView.load(URLRequest(url: url))
        }
    }
    
    // WKNavigationDelegate methods here
}

操作方法

ページの読み込みを制御する

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    // URLのホスト名がexample.comの場合のみページを読み込む
    if let host = navigationAction.request.url?.host, host.contains("example.com") {
        decisionHandler(.allow)
    } else {
        decisionHandler(.cancel)
    }
}

ページの読み込みが完了したことを検知する

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    // ページの読み込みが完了したことを検知する処理
}

ページの読み込みが失敗したことを検知する

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    // ページの読み込みが失敗したことを検知する処理
}

SSL証明書の検証を制御する

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    guard let urlResponse = navigationResponse.response as? HTTPURLResponse else {
        decisionHandler(.allow)
        return
    }
    
    // SSL証明書の検証を無視する
    if urlResponse.statusCode == 200 {
        decisionHandler(.allow)
    } else {
        decisionHandler(.cancel)
    }
}

最後に

iOSアプリ開発をしています。
主にSwiftですが、最近は熱が入ってきてFlutterも🦾
色々やってます。もし良かったら見てってください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?