欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WKWebView使用

程序员文章站 2022-03-20 14:57:39
...

Demo链接:https://github.com/3KK3/WKWebViewAndLoadNativeAddressbook

WKWebView是苹果iOS8后推出的用来替代UIWebView的新控件,iOS9后又推出缓存相关的API。

iOS端调用js端方法:
 //直接调用js 
  webView.evaluateJavaScript("hi()", completionHandler: nil)
 //调用js带参数 
  webView.evaluateJavaScript("hello('liuyanwei')", completionHandler: nil) 
  //调用js获取返回值 
  webView.evaluateJavaScript("getName()") { (any,error) -> Void in
   NSLog("%@", any as! String) 
}

注:WKWebView绝大多数睡醒支持kvo
比如想要在网页加载完成后执行某些操作,可以监控WKWebView的loading属性:

  self.webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil)

然后在监控方法执行操作:

  override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "loading" {
      print("loading")
    } 
    // 已经完成加载时,我们就可以做我们的事了
    if !webView.loading {
     //TODO:
    }
  }
WKWebView还支持iOS端往js端注入代码
    // 创建一个webiview的配置项
    let configuretion = WKWebViewConfiguration()

    // 添加一个JS到HTML中,这样就可以直接在JS中调用我们添加的JS方法
    let script = WKUserScript(source: "function showAlert() { alert('在载入webview时通过Swift注入的JS方法'); }",
      injectionTime: .AtDocumentStart,// 在载入时就添加JS
      forMainFrameOnly: true) // 只添加到mainFrame中

    configuretion.userContentController.addUserScript(script)
js端调用iOS端方法

1).js端代码要求:
在js端点击事件处,想iOS端发送message信息,代码格式为:


<script type="text/javascript">

   function callJsAlert() {
    alert('Objective-C call js to show alert');    //注意①
    window.webkit.messageHandlers.消息名.postMessage({body: 'this body can be received by iOS platform'});
   }
</script>

注意①:WKWebView中,js端的弹框alert事件,需要在iOS端通过WKUIDelegate的三个代理runJavaScriptAlertPanelWithMessage runJavaScriptConfirmPanelWithMessage和runJavaScriptTextInputPanelWithPrompt来实现。比如上面js代码中的alert('Objective-C call js to show alert');事件 ,需要在iOS端:

override func viewDidLoad() {
  self.webView.UIDelegate = self
}

// MARK: - WKUIDelegate
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
  let alert = UIAlertController(title: "Tip", message: message, preferredStyle: .Alert)
  alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (_) -> Void in
    // We must call back js
    completionHandler()
  }))
  
  self.presentViewController(alert, animated: true, completion: nil)
}

func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
  let alert = UIAlertController(title: "Tip", message: message, preferredStyle: .Alert)
  alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (_) -> Void in
    completionHandler(true)
  }))
  alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (_) -> Void in
    completionHandler(false)
  }))
  
  self.presentViewController(alert, animated: true, completion: nil)
}

//带输入框的alertview
func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) {
    
  let alert = UIAlertController(title: prompt, message: defaultText, preferredStyle: .Alert)
  
  alert.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in
    textField.textColor = UIColor.redColor()
  }
  alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (_) -> Void in
    completionHandler(alert.textFields![0].text!)
  }))
  
  self.presentViewController(alert, animated: true, completion: nil)
}

2).iOS端代码要求:

  // 创建一个webiview的配置项
    let configuretion = WKWebViewConfiguration()

    // 添加一个名称,就可以在JS通过这个名称发送消息:
    // window.webkit.messageHandlers.消息名.postMessage({body: 'xxx'})
    //name需要跟js端的消息名保持一致
    configuretion.userContentController.addScriptMessageHandler(self, name: "AppModel")
    configuretion.userContentController.addScriptMessageHandler(self, name: "AppModel1")

然后实现WKScriptMessageHandler的代理方法:

    // MARK: - WKScriptMessageHandler
    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        print(message.body)
        if message.name == "AppModel" {
            print("message name is AppModel")
        }
        
        if message.name == "AppModel1" {
            //TODO:
        }
    }