[iOS] [Swift] WKWebViewでtarget=“_blank”に対応する


デリゲートを埋め込む

WKUIDelegate を埋め込む

class MyViewController: WKNavigationDelegate, WKUIDelegate {
}

_webview.uiDelegate をセットする

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
    }

webView:createWebViewWithConfiguration:メソッドを実装

対象URL(target=“_blank”)をSafariで開く

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            if  let url = navigationAction.request.url {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
        return nil
    }

参考