WebView 與App互傳資訊

WebView 與App互傳資訊
01.編輯 ViewControl.swift

在class ViewController: UIViewController,加入 WKUIDelegate, WKScriptMessageHandler 

變成 class ViewController: UIViewController,WKUIDelegate, WKScriptMessageHandler {

在class ViewController: UIViewController,WKUIDelegate, WKScriptMessageHandler {} 中新增
這區段處理每一個對應的作業

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    switch message.name {
    case "openURL":
        let url01 = URL(string: message.body as! String)!
        UIApplication.shared.open(url01)
    case "shareLine":
        let l_str = message.body  as! String
        let u_str = l_str.components(separatedBy: "?url=")
        let lineURL=URL(string: "line://msg/text/" + u_str[1])
        if UIApplication.shared.canOpenURL( lineURL! ) {
            UIApplication.shared.open(lineURL!, options: [:],completionHandler: nil)
        }else{
            guard let url01 = URL(string: message.body  as! String) else {return}
            UIApplication.shared.open(url01)
        }
    default:
            break
    }
}

 

02.override func loadView() {} 區段中加入

    override func loadView() {
        let prefs=WKWebpagePreferences();
        prefs.allowsContentJavaScript = true //ios 14 後才有支援
        
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.defaultWebpagePreferences = prefs
        //以下為註冊與前端網頁溝通用 Func
        //需要用到的都要在這先註冊
        webConfiguration.userContentController = WKUserContentController()
        webConfiguration.userContentController.add(self ,name : "openURL")
        webConfiguration.userContentController.add(self ,name : "shareLine")
        webConfiguration.userContentController.add(self ,name : "shareFB")
        webConfiguration.userContentController.add(self ,name : "setBadge")

        webView = WKWebView(frame: .zero, configuration: webConfiguration)

        view = webView
}