Swift webview:如何从javascript正确调用swift代码?

前端之家收集整理的这篇文章主要介绍了Swift webview:如何从javascript正确调用swift代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图让我的 JavaScript与swift代码交互,但不幸的是我没有成功.

目前,我只是尝试更改标题颜色并显示一条消息,就像您将在下面的代码中看到的.

这是我的(index.html)代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Test</title>
  5. <Meta charset="UTF-8">
  6. </head>
  7. <body>
  8. <h1>WebView Test</h1>
  9. <script type="text/javascript" src="main.js"></script>
  10. </body>
  11. </html>

这是我的(main.js -JavaScript)代码

  1. function callNativeApp () {
  2. try {
  3. webkit.messageHandlers.callbackHandler.postMessage("Send from JavaScript");
  4. } catch(err) {
  5. console.log('error');
  6. }
  7. }
  8.  
  9. setTimeout(function () {
  10. callNativeApp();
  11. },5000);
  12.  
  13. function redHeader() {
  14. document.querySelector('h1').style.color = "red";
  15. }

这是我的(ViewController.swift)代码

  1. import UIKit
  2. import WebKit
  3.  
  4. class ViewController: UIViewController,WKScriptMessageHandler {
  5.  
  6. @IBOutlet var containerView : UIView! = nil
  7.  
  8. var webView: WKWebView?
  9.  
  10. override func loadView() {
  11. super.loadView()
  12.  
  13. var contentController = WKUserContentController();
  14. var userScript = WKUserScript(
  15. source: "redHeader()",injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,forMainFrameOnly: true
  16. )
  17. contentController.addUserScript(userScript)
  18. contentController.addScriptMessageHandler(
  19. self,name: "callbackHandler"
  20. )
  21.  
  22. var config = WKWebViewConfiguration()
  23. config.userContentController = contentController
  24.  
  25. self.webView = WKWebView()
  26. self.view = self.webView!
  27. }
  28.  
  29. override func viewDidLoad() {
  30. super.viewDidLoad()
  31. // Do any additional setup after loading the view,typically from a nib.
  32. var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index",ofType: "html")!)
  33. var req = NSURLRequest(URL: url)
  34. self.webView!.loadRequest(req)
  35. }
  36.  
  37. func userContentController(userContentController: WKUserContentController!,didReceiveScriptMessage message: WKScriptMessage!) {
  38. if(message.name == "callbackHandler") {
  39. println("JavaScript is sending a message \(message.body)")
  40. } }
  41.  
  42. override func didReceiveMemoryWarning() {
  43. super.didReceiveMemoryWarning()
  44. // Dispose of any resources that can be recreated.
  45. }
  46.  
  47.  
  48. }
您正确设置了所有设置,但是您没有将WKWebViewConfiguration实例提供给WKWebView.由于配置有Javascript / Swift桥梁的细节,您不能来回说话.
  1. override func loadView() {
  2. // ...
  3. var config = WKWebViewConfiguration()
  4. config.userContentController = contentController
  5.  
  6. self.webView = WKWebView(frame: self.view.frame,configuration: config)
  7. self.view = self.webView!
  8. }

猜你在找的Swift相关文章