我要执行以下操作:
我的JavaScript函数,用于向Swift发送消息:
function clicar( id, categ ) {
window.webkit.messageHandlers.jsHandler.postMessage( "{ 'id' : "+id+", 'categ' : '" + categ + "' }" );
}
我的Swift收到消息并处理http请求:
extension FirstViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler" {
if let messageBody = message.body as? [String: Any], let id = messageBody["id"] as? Int {
self.getData( id )
}
}
}
func getData( id: Int ) {
let url = URL( string: "http://192.168.1.11/inter/app/api/varModel/event.php?categ=" + String(id) )
_ = URLSession.shared.dataTask(with: url!) { (data, req, error) in
if req != nil { }
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
var textJson = json...
print( text )
// until here OK
// FAILED HERE
self.wk.evaluateJavaScript("mountCateg( '\(textJson)' );", completionHandler: nil)
} catch {
print( erro as Any )
}
}
}.resume()
}
JavaScript处理DOM:
function mountCateg( data ) {
let text = "";
for ( let i = 0; i < data.length; i++ ) {
text += "<div class='itemCateg' i='"+data[i].id+"' o='"+data[i].idOrganizer+"'>";
text += "<img class='imgEvento' src='http://192.168.1.11/inter/site/imgEvents/"+data[i].imagem+"'>";
text += "<p class='diaEvento'>"+data[i].dataHora+"</p>";
text += "<p class='nomeEvento'>"+data[i].nome+"</p>";
text += "<p class='localEvento'>"+data[i].cidade+"/"+data[i].uf+"</p>";
text += "</div>";
}
$('#listaEventos').html( text );
}
它给我这个错误:
如何快速处理DOM更改?
-----编辑-----
我尝试过,但错误仍然存在。
DispatchQueue.main.async {
self.wk.evaluateJavaScript("mountCateg( '\(textJson)' );", completionHandler: nil)
}
我也尝试过:
extension FirstViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler" {
if let messageBody = message.body as? [String: Any], let id = messageBody["id"] as? Int {
self.getData( id )
DispatchQueue.main.async {
self.wk.evaluateJavaScript("mountCateg( '\(textJson)' );", completionHandler: nil)
}
}
}
没有错误,但也没有任何反应!没用
答案 0 :(得分:1)
URLSession.shared.dataTask
完成块不在主线程上运行。只需在主线程上调用evaluateJavaScript
即可解决该问题:
func getData( id: Int ) {
let url = URL( string: "http://192.168.1.11/inter/app/api/varModel/event.php?categ=" + String(id) )
_ = URLSession.shared.dataTask(with: url!) { (data, req, error) in
if req != nil { }
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
var textJson = json...
print( text )
DispatchQueue.main.async { // call evaluateJavascript on the main thread
self.wk.evaluateJavaScript("mountCateg( '\(textJson)' );", completionHandler: nil)
}
} catch {
print( erro as Any )
}
}
}.resume()
}