WKWebView

作者: 纳兰沫 | 来源:发表于2019-11-21 16:53 被阅读0次

    属性

    AirPlay 隔空播放 主要用在TV上面 
    Inline Playback 如果选中就是播放视频的时候允许用h5的方式播放 如果不选中就是用苹果原生的播放
    Picture-in-Picture 画中画 置顶播放
    
    webView.isLoading
    webView.reload()
    webView.reloadFromOrigin()
    webView.stopLoading()
            //
    webView.goBack()
    webView.goForward()
    //用户访问网页的历史
    webView.backForwardList
    

    自定义根视图

     var webView: WKWebView!
        //自定义根视图
        override func loadView() {
        
           let config = WKWebViewConfiguration()
           
           webView = WKWebView(frame: .zero, configuration: config)
            //可以左滑右滑达到前进后退的目的
           webView.allowsBackForwardNavigationGestures = true
           view = webView
        }
    

    把网页上的弹框都转化为iOS的原生弹框

    //把网页上的弹框都转化为iOS的原生弹框
    extension ViewController: WKUIDelegate {
        
        //警告框
        func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
            
            let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
                completionHandler()
            }))
            present(alert, animated: true, completion: nil)
        }
        
        //确认框
        func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
            
            let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
                completionHandler(false)
            }))
            alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
                completionHandler(true)
            }))
            present(alert, animated: true, completion: nil)
        }
        
        //输入框
        func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
            
            let alert = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
            alert.addTextField { (textField) in
                textField.placeholder = defaultText
            }
            alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
                completionHandler(alert.textFields?.last?.text)
            }))
            present(alert, animated: true, completion: nil)
        }
    }
    

    设置小菊花

    var spinner: UIActivityIndicatorView!
    spinner = UIActivityIndicatorView(style: .whiteLarge)
    spinner.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8008882705)
    spinner.layer.cornerRadius = 10
    spinner.translatesAutoresizingMaskIntoConstraints = false
    webView.addSubview(spinner)
            
    //设置x方向的约束 激活
    spinner.centerXAnchor.constraint(equalTo: webView.centerXAnchor).isActive = true
    spinner.centerYAnchor.constraint(equalTo: webView.centerYAnchor).isActive = true
    spinner.widthAnchor.constraint(equalToConstant: 80).isActive = true
    spinner.heightAnchor.constraint(equalToConstant: 80).isActive = true
    
    extension ViewController: WKNavigationDelegate {
        
        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            print(#function)
            spinner.startAnimating()
        }
        
        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            print(#function)
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print(#function)
            spinner.stopAnimating()
            spinner.removeFromSuperview()
        }
        
        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            print(#function)
            spinner.stopAnimating()
            spinner.removeFromSuperview()
        }
    }
    

    是否加载

    //决定是否加载 请求之前
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            print(#function)
            //当主机是www.google.com 的时候 就不加载 外部浏览器加载
            if let url = navigationAction.request.url {
                if url.host == "www.google.com" {
                    UIApplication.shared.open(url)
                    decisionHandler(.cancel)
                    return
                }
            }
            decisionHandler(.allow)
        }
    
    //收到相应之后 决定是否要加载
        func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
            
            print(#function)
            if let httpResponse = navigationResponse.response as? HTTPURLResponse,
                httpResponse.statusCode == 200{
                decisionHandler(.allow)
                return
            }
            decisionHandler(.cancel)
        }
    

    加载html代码

     func handleHTMLFile() {
            let url = Bundle.main.url(forResource: "HomePage", withExtension: "html")
            //url!.deletingLastPathComponent() 访问上层文件夹内容
            webView.loadFileURL(url!, allowingReadAccessTo: url!.deletingLastPathComponent())
        }
    

    加载Js代码

    func handleJS() {
            webView.evaluateJavaScript("") { (res, error) in
                print(res)
            }
        }
    

    检测WKWebView的加载进度

     webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            
            if keyPath == #keyPath(WKWebView.estimatedProgress) {
                print(webView.estimatedProgress)
            }
        }
    
    销毁observer
    deinit {
            webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
        }
    

    交互

    config.userContentController.add(self, name: "user")
    
    extension ViewController: WKScriptMessageHandler {
        
        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            
            if message.name == "user" {
                //可以给数据进行交互
                
            }
        }    
    }
    

    截图

    //全屏截图
     webView.takeSnapshot(with: nil) { (image, error) in
           guard let image = image else{ return }
           print(image.size)
     }
    
    // 设置大小截取相应屏幕
    let config = WKSnapshotConfiguration()
       config.rect = CGRect(x: 0, y: 0, width: 200, height: 200)
       webView.takeSnapshot(with: config) { (image, error) in
       guard let image = image else{ return }
       print(image.size)
     }
    

    Cookie

    //读取cookie的value 和 删除 cookie
        func handleCookie() {
            
            webView.configuration.websiteDataStore.httpCookieStore.getAllCookies{ cookies in
                for cookie in cookies {
                    if cookie.name == "auth" {
                        self.webView.configuration.websiteDataStore.httpCookieStore.delete(cookie)
                    }else{
                        print(cookie.value)
                    }
                    
                }
            }
            
        }
    

    相关文章

      网友评论

          本文标题:WKWebView

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