LoginSignup
5
2

More than 3 years have passed since last update.

[Swift] WebViewからWebViewページの特定のリンクをタップしたときの挙動を制御する

Last updated at Posted at 2017-09-05

WebViewからページ内のリンクをタップした時にアプリ側で何かしらの制御をする

今回WebViewページから特定のリンクをタップするとアプリ内で検知してViewを表示するなり、メーラーを起動するようなものを作ってみたのでメモ。

WebViewController.swift
    //
    // 省略
    //

    // このメソッドで特定のリンクを検知してアプリ内で制御する
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        //タップしたリンクのURLを取得
        let url = navigationAction.request.url?.absoluteString
        // aaaの場合はあるviewをmodalで出す
        if url == "aaa" {
            let storyboard = UIStoryboard(name: "", bundle: nil)
            let nextView = storyboard.instantiateInitialViewController()
            self.present(nextView!, animated: true, completion: nil)
            decisionHandler(.cancel)
            return
        }
        // bbbの場合はメーラーを起動する 
        else if url == "bbb" {
            self.sendMail()
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }
}

// MARK: - MFMailComposeViewControllerDelegate メーラーを起動する
extension WebViewController: MFMailComposeViewControllerDelegate {
    func sendMail() {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setSubject("[お問い合わせ]")
            let toRecipients = ["xxx@xxx.xx"]
            mail.setToRecipients(toRecipients)
            mail.setMessageBody("お問い合わせ内容", isHTML: false)
            present(mail, animated: true, completion: nil)
        } else {
            print("送信できません")
        }
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result {
        case .cancelled:
            print("キャンセル")
        case .saved:
            print("下書き保存")
        case .sent:
            print("送信成功")
        default:
            print("送信失敗")
        }
        dismiss(animated: true, completion: nil)
    }
}

・参考
https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455641-webview

5
2
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
5
2