2016-01-22 61 views
1

我想從iOS應用中的swift文件傳遞數據到我擁有的JavaScript文件。我擡起頭,evaluateJavaScript方法,它不工作。不知道我做錯了什麼。這是我正在嘗試的。任何幫助,將不勝感激。Swift傳遞數據到Javascript

var webView: WKWebView 
let config = WKWebViewConfiguration() 
let loginScriptURL = NSBundle.mainBundle().pathForResource("addComment", ofType: "js") 
let addCommentMessageHandler = "addComment" 

required init?(coder aDecoder: NSCoder) { 
    self.webView = WKWebView(frame: CGRectZero, configuration: config) 
    super.init(coder: aDecoder) 
    self.webView.navigationDelegate = self 
    config.userContentController.addScriptMessageHandler(self, name: addCommentMessageHandler) 
    let scriptContent = try? String(contentsOfFile:loginScriptURL!, encoding:NSUTF8StringEncoding) 
    let script = WKUserScript(source: scriptContent!, injectionTime: .AtDocumentEnd, forMainFrameOnly: true) 
    config.userContentController.addUserScript(script) 
    webView.evaluateJavaScript("storeAndShow(\(DataService.shared.theComment))", 
     completionHandler: nil) 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 

    setUpView() 
} 

func setUpView() { 
    view.addSubview(webView) 
    webView.translatesAutoresizingMaskIntoConstraints = false 
    let height = NSLayoutConstraint(item: webView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: -44) 
    let width = NSLayoutConstraint(item: webView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0) 
    view.addConstraints([height, width]) 

    webView.loadRequest(NSURLRequest(URL:NSURL(string:"https://blah.com)!)) 
} 

正如您所看到的,我正嘗試使用一些數據調用storeAndShow。 storeAndShow方法在我的JavaScript文件中。

+0

您是否將視圖設置爲WKScriptMessageHandler委託並實現了didReceiveScriptMessage處理程序來處理結果? –

回答

0

documentation說:

討論

的方法發送腳本評價(或錯誤),以完成處理的結果。

但是您將nil傳遞給完成處理程序。你應該檢查它是否重新調整錯誤,也許有更多關於這個問題的信息。

相關問題