Evaluate and Resolve a Promise in WKWebView
This sums up every iOS development I've ever done. So I am very new to fast development or iOS development for that matter.
What I am trying to accomplish is behaving almost like jsonp when doing a cross domain ajax request in javascript (if you know how it works ...)
The problem I have is that I cannot evaluate the javascript and return something that behaves asynchronously. For example, get anything from indexedDB in webview
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'}
})
*/
}
My helper function
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)
}
My message handler
/// 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
}
}
+3
source to share
No one has answered this question yet
Check out similar questions: