当前位置: 首页 > 工具软件 > Swift Lang > 使用案例 >

【iOS】【swift】WKWebView与H5之间交互传值

邬弘化
2023-12-01

1、首先创建wkWebViewprogressView

    fileprivate var wkWebView =  WKWebView()
    fileprivate var progressView = UIProgressView()

2、然后创建WKWebViewConfiguration可以进行自定义配置WKWebView

        let config = WKWebViewConfiguration()
        // 设置偏好设置
        config.preferences = WKPreferences()
        // 默认为0
        config.preferences.minimumFontSize = 10
        // 默认认为YES
        config.preferences.javaScriptEnabled = true
        // 在iOS上默认为NO,表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = true
        // web内容处理池
        config.processPool = WKProcessPool()
        // 通过JS与webview内容交互
        config.userContentController = WKUserContentController()
        // 注入JS对象名称AppModel,当JS通过AppModel来调用时,
        // 我们可以在WKScriptMessageHandler代理中接收到
        config.userContentController.add(self, name: "TakePicture")
        config.userContentController.add(self, name: "PhotoAlbum")
        config.userContentController.add(self, name: "ExitAPP")

3、紧接着开始创建WKWebView和进度条progressView

        self.wkWebView = WKWebView(frame:self.view.frame, configuration: config)
        wkWebView.navigationDelegate = self
        wkWebView.uiDelegate = self
        wkWebView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        wkWebView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
        self.view.addSubview(wkWebView)
        wkWebView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        progressView.progressTintColor = UIColor.red
        progressView.trackTintColor = UIColor.blue
        self.view.addSubview(self.progressView)
        progressView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(25)
            make.height.equalTo(3)
        }

4、WKWebView开始加载网页

加载本地网页

            let bundlePath = Bundle.main.bundlePath
            let filePath = "file://\(bundlePath)/test.html"
            guard let url = URL(string: filePath) else {
                return
            }
            wkWebView.load(URLRequest(url: url))

加载URL

            wkWebView.load(URLRequest(url: URL(string: address)!))            

5、显示监听网页加载进度

extension LCWebViewController:WKNavigationDelegate,WKUIDelegate
{
    // 监听网页加载进度
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "estimatedProgress" {
            self.progressView.progress = Float(self.wkWebView.estimatedProgress)
        }
        
        if !self.wkWebView.isLoading {
            UIView.animate(withDuration: 0.5, animations: {
                self.progressView.alpha = 0
            })
        }
        
    }
}

6、接收H5传值并处理

extension LCWebViewController:WKScriptMessageHandler
{
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //拍照
        if message.name == "TakePicture" {
            
           let cameraViewController = LCCameraViewController()
            cameraViewController.finishCallBack = {[weak self] imageBase64String in
                let message =  "jsReceiveImage(\"\(imageBase64String)\")"
                self!.swiftCallJS(string: message, success: nil, fail: nil)
            }
            self.navigationController?.pushViewController(cameraViewController, animated: true)
        }
        
        //相册
        if message.name == "PhotoAlbum" {
            let photoPicker =  UIImagePickerController()
            photoPicker.delegate = self
            photoPicker.sourceType = .photoLibrary
            //在需要的地方present出来
            self.present(photoPicker, animated: true, completion: nil)
        }
        
        //退出APP
        if message.name == "ExitAPP" {
            let array = []
            print(array[2])
        }
    }
}

7、swift原生完成之后,将结果传给H5

    /// swift调JS
    /// - Parameters:
    ///   - message: "jsReceiveImage(\"图片base64\")"
    ///   - success: <#success description#>
    ///   - fail: <#fail description#>
    func swiftCallJS(message:String, success:(()->())?, fail:(()->())?) {
        if !self.wkWebView.isLoading {
            self.wkWebView.evaluateJavaScript(message, completionHandler: { (response, error) in
                if !(error != nil){
                    if success != nil {
                        success!()
                    }
                }else{
                    if fail != nil {
                        fail!()
                    }
                }
            })
        }
    }

8、H5 网页代码书写方法


<!DOCTYPE html>
<html lang="en">
<head>
    <title>LCWebView</title>
    <style>
        button {
            font-size: 30px;
            width: 500px;
            height: 100px;
            display: block;
            margin-top: 5px;
        }
    </style>
    <script type="text/javascript">
        function useCamera() {
            window.webkit.messageHandlers.TakePicture.postMessage(null);
        }
        function usePhoto() {
            window.webkit.messageHandlers.PhotoAlbum.postMessage(null);
        }
        function useExitAPP() {
            window.webkit.messageHandlers.ExitAPP.postMessage(null);
        }
        function jsReceiveImage(imageData) {
            alert(imageData);
        }
    </script>
</head>
<body>
    <button onclick="useCamera()" id="openCameraButton">useCamera</button>
    <button onclick="usePhoto()" id="openPhotoButton">usePhoto</button>
    <button onclick="useExitAPP()" id="ExitAPP">useExitAPP</button>
</body>
</html>

 类似资料: