iOS 开发之路(使用WKWebView加载Html5) 四

寻技术 Html/CSS 2023年11月30日 97

  基于Swift 3 、 Xcode 8 、 iOS 10 下的WKWebView的使用。

  首先是WKWebView的基本用法:

    var wk:WKWebView! 
    var progBar:UIProgressView!    //定义的进度条
    override func viewDidLoad() {
        super.viewDidLoad()
        self.wk = WKWebView(frame: self.view.frame)
        let theConfiguration = WKWebViewConfiguration()
        theConfiguration.userContentController = WKUserContentController() // 通过js与webview内容交互配置
        let  frame = CGRect(x: ,y : , width: self.view.frame.width, height:self.view.frame.height) //定位wk位置
        wk = WKWebView(frame: frame, configuration: theConfiguration)
        wk.allowsLinkPreview = true
        self.wk.load(NSURLRequest(url:NSURL(string:"http://www.baidu.com/")! as URL) as URLRequest) //要在info.plist中添加对http的支持
        self.view.addSubview(self.wk)
        // add your self view here
        // add back <- icon to back to previous page
    }

  上面的其实很简单,很多教程里其实都有。下面讲一下如何实现进度条。这个也不难。

    //视图已经加载完后执行
    override func viewDidAppear(_ animated: Bool){
        super.viewDidAppear(animated)

        self.wk.uiDelegate = self //实现协议,进度条和获取网页标题需要用到
        self.wk.navigationDelegate = self //网页间前进后退要用到
     
        //生成进度条
        progBar = UIProgressView(frame: CGRect(x: , y: , width: self.view.frame.width, height: ))
        progBar.progress = 0.0
        progBar.tintColor = UIColor.blue
        self.view.addSubview(progBar)
        //注册进度条监听事件
        self.wk.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        //注册网页标题监听事件
        self.wk.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
  
    }

  上面的UIDelegate要在类前添加协议:

class LxxmForSwift: UIViewController, WKNavigationDelegate, WKUIDelegate, UINavigationControllerDelegate {
}

  关于WKUIDelegate、UINavigationDelegate大家可以去Apple开发中心查看文档,保证会加深印象。

  进度条、网页标题变动监听事件的具体实现:

    //这里添加了estimatedProgrees和title两个监听事件
   override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            progBar.setProgress(Float(wk.estimatedProgress), animated: true)
            if(self.wk.estimatedProgress >= 1.0){
                UIView.animate(withDuration: 0.3, delay: 0.1, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 
                })
            }
            
        } else if keyPath == "title" {
            self.titleForWeb.title = self.wk.title //这里titleForWeb是我自己定义的一个导航bar
            print(wk.title!)
        }
    }

  注意,添加完的监听事件需要有对应的注销事件:

    override func viewWillDisappear(_ animated: Bool) {
        wk.removeObserver(self, forKeyPath: "estimatedProgress")
        wk.removeObserver(self, forKeyPath: "title")
    }

  我们都知道,WKWebView比UIWebView占用更少内存,性能更好。不过UIWebView可以直接实现JS中alert实现,而前者对JS里的alert事件重新封装了,必须实现WKUIDelegate协议:

    
  //把这两个方法加到代码里,配合之前的 self.wk.uiDelegate = self 即可。

  //监听js调用提示框 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: { (action) in completionHandler() })) self.present(alert, animated: true, completion: nil) } // 监听通过JS调用q确认框 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: .default, handler: { (action) in completionHandler(true) })) alert.addAction(UIAlertAction(title: "取消", style: .default, handler: { (action) in completionHandler(false) })) self.present(alert, animated: true, completion: nil) }

  关于WKWebView中Html5图片上传,下一篇随笔我会说一下。

 

关闭

用微信“扫一扫”