美文网首页
swift WKWebView 原生和h5交互

swift WKWebView 原生和h5交互

作者: 不言弃zxf | 来源:发表于2020-03-09 14:10 被阅读0次

    WKWebView 初始化设置

    let Configuration = WKWebViewConfiguration()

            let controller = WKUserContentController()

            let Preferences = WKPreferences()

            Configuration.preferences = Preferences

            controller.add(self, name: "doActionMsg")  //  注入js方法

            Configuration.preferences.javaScriptEnabled = true

            Configuration.preferences.javaScriptCanOpenWindowsAutomatically = true

            Configuration.allowsInlineMediaPlayback = true

            if #available(iOS 9.0, *) {

                Configuration.requiresUserActionForMediaPlayback = false

            } else {

                // Fallback on earlier versions

            }

            Configuration.userContentController = controller

            let processPool = WKProcessPool()

            Configuration.processPool = processPool

            webView = WKWebView(frame: CGRect(x: 0, y: 0, width: Wi, height: Hi-navigationTopHeight), configuration: Configuration)

            webView.backgroundColor = UIColor.white

            let request = URLRequest(url: URL(string: self.urlString)!)

    //        webView.navigationDelegate = self

    //        webView.uiDelegate = self

            webView.load(request as URLRequest)

            webView.scrollView.showsVerticalScrollIndicator = true

            webView.scrollView.delegate = self

            self.view.addSubview(webView)

    WKWebView代理方法

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

            if message.name == "doActionMsg" {  // 约定好的方法

    if let bodyStr:String = message.body as? String { //  返回参数

                    let dict:Dictionary = getDictionaryFromJSONString(jsonString: bodyStr)

                    print("dict____",dict)

    }

    }

    }

    相关文章

      网友评论

          本文标题:swift WKWebView 原生和h5交互

          本文链接:https://www.haomeiwen.com/subject/rrkpdhtx.html