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

  • 2019 年 10 月 5 日
  • 筆記

  基於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 即可。

  關於WKWebView中Html5圖片上傳,下一篇隨筆我會說一下。