Native側で、JavaScript機能の呼び出し、
func getImages() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
appWebView?.evaluateJavaScript(
"getLastImages()") { (result, error) -> Void in
if error != nil {
print(error as Any)
}
print(result as Any)
}
}
}
JavaScriptからJsonポストして、
getLastImages: function() {
let message = {
cmd: 'lastimages',
count: '1',
callbackFunc: function(responseAsJSON) {
let response = JSON.parse(responseAsJSON)
let image = response['image']
if(image){
self.form.image_white = image
}
}.toString()
}
window.webkit.messageHandlers.native.postMessage(message)
}
Native側のHandlerは、
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let sentData = message.body as! NSDictionary
let command = sentData["cmd"] as! String
var response = Dictionary<String,AnyObject>()
if command == "lastimages"{
appWebView?.evaluateJavaScript(
"document.getElementById('fetchimage').style.display = 'none';") { (result, error) -> Void in
if error != nil {
print(error as Any)
}
print(result as Any)
}
concurrentQueue.sync {
var imageString = [String]()
imageString = imgProcessHandler.identifyFetchResult()
response["image"] = imageString as AnyObject
let callbackString = sentData["callbackFunc"] as? String
self.sendResponse(aResponse: response, callback: callbackString)
}
}
}