iOS 開發之路(使用WKWebView加載Html5) 四


  基於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: 0,y : 0, 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: 0, y: 0, width: self.view.frame.width, height: 30))
        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 = 0
                })
            }
            
        } 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圖片上傳,下一篇隨筆我會說一下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM