评估并解决WKWebView中的承诺

时间:2017-03-29 14:25:12

标签: javascript ios swift3 promise wkwebview

这是我所做过的所有iOS开发的总结。所以我对swift或任何iOS开发都很​​新。

我想要完成的是在javascript中执行跨域ajax请求时的行为几乎就像jsonp(如果你知道它是如何工作的......)

我有一个问题,我无法评估javascript并找回行为异步的东西。例如,从webview中的indexedDB获取任何内容

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after lvaring the view, typically from a nib.
    self.webview = WKWebView()
    self.i = 0

    let preferences = WKPreferences()
    let configuration = WKWebViewConfiguration()

    preferences.javaScriptEnabled = true

    configuration.preferences = preferences
    configuration.userContentController.add(self as WKScriptMessageHandler,name: "bridge")

    self.webview = WKWebView(frame: self.view.frame, configuration: configuration)
    webview.navigationDelegate = self
    webview.isHidden = true
    webview.load(URLRequest(url: URL(string: "http://example.com")!))

    /* 
    help...
    don't know how closure & completion Handler (callbacks) works in swift
    runjs("Promise.resolve({msg: 'hello world'})", completionHandler: (result) -> Void) {
        print(result) // expecting it to be {msg: 'hello world'}
    })
    */
}

我的助手功能

func runjs(input: String, completeHandler: Any) {
    self.i = self.i + 1
    // TODO: store the completeHandler in a some HashMap with `i` as the key

    let js = "Promise.resolve(" + input + ").then(res => webkit.messageHandlers.bridge.postMessage({i: " + String(self.i) + ", data: res}))"

    webview.evaluateJavaScript(js)
}

我的留言处理程序

/// Adds support for the WKScriptMessageHandler to ViewController.
extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController,
                               didReceive message: WKScriptMessage) {

        let json:NSDictionary = message.body as! NSDictionary
        let i:Int = json["i"] as! Int
        let data:NSDictionary = json["data"] as! NSDictionary

        // TODO: get the complete handler from a HashMap[i]
        // TODO: call the complete handler with data as argument
        // TODO: remove the complete handler from the HashMap
    }
}

0 个答案:

没有答案