2016-11-23 36 views
5

我想從UIWebView中的JavaScript函數調用Swift在iOS 10中進行調用。我已經設置了一個非常基本的項目,只是爲了試着讓它工作,代碼如下。從UIWebView對Swift進行Javascript調用

import UIKit 

class ViewController: UIViewController, UIWebViewDelegate {  
    @IBOutlet var webView: UIWebView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let url = Bundle.main.url(forResource: "products", withExtension: "html") 
     let request = NSURLRequest(url: url! as URL) 
     webView.loadRequest(request as URLRequest) 
    } 

    @IBAction func closeDocumentViewer() { 
     displayView.isHidden = true; 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
} 

如果我只是一個接收來自javascript函數的字符串,那麼我將不得不添加到上面?

回答

1

您必須自定義URL Schememyawesomeapp和攔截請求它使用:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool 

消防使用window.location=myawesomeapp://hello=world本機代碼的調用,而params你request.URL.query在本機代碼通過得到查詢。

欲瞭解更多信息,請參閱我的問題有關UIWebView在這兒:JavaScript synchronous native communication to WKWebView

9

我會建議尋找到使用WKWebView代替UIWebView。然後您將不需要註冊自定義URL方案。此外,UIWebView已經過時,WKWebView具有很多優點,特別是性能和渲染,因爲它在單獨的過程中運行。

鏈接到蘋果的文檔和信息,建議使用WKWebView https://developer.apple.com/reference/webkit/wkwebview/

重要

中的iOS 8.0和OS X 10.10開始,使用WKWebView Web內容添加到您>應用程序。不要使用UIWebView或WebView。

這就是說,它的設置非常簡單的一個原生的JavaScript橋:

import WebKit 

class ViewController: UIViewController, WKScriptMessageHandler { 
    var webView: WKWebView? 
    override func loadView() { 
     super.loadView() 

     webView = WKWebView(frame: self.view.frame) 
     webView?.configuration.userContentController.add(self, name: "scriptHandler") 

     self.view.addSubview(webView!) 
    } 

    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { 
     print("Message received: \(message.name) with body: \(message.body)") 
    } 
// rest of code 
} 

然後在你的JavaScript代碼,調用它:

window.webkit.messageHandlers["scriptHandler"].postMessage("hello"); 

我寫了一個利用庫這並增加了一些花哨的JavaScript語法。 https://github.com/tmarkovski/BridgeCommander

要使用它,只是參考的項目(或添加快捷和JavaScript文件到您的Xcode項目),並調用

webView = WKWebView(frame: self.view.frame) 
    let commander = SwiftBridgeCommander(webView!) 

    commander.add("echo") { 
     command in 
     command.send(args: "You said: \(command.args)") 
    } 

然後,您就可以使用回調的語法在JavaScript這樣

var commander = new SwiftBridgeCommander(); 
commander.call("echo", "Hello", function(args) { 
     // success callback 
    }, function(error) { 
     // error callback 
}); 
+0

我正在使用wkwebview,但wkwebview可能會導致死角。就像它不是將cookie與nshttpcookiestrorage同步 – Atif

+0

是的,這是WKWebView的一個缺點。它在獨立進程中運行Web引擎,無法訪問運行時內存。 –

+0

使用WKWebView檢查WKWebsiteDataStore文檔的cookie管理 - https://developer.apple.com/documentation/webkit/wkwebsitedatastore –