Swift在后台线程中更新WKWebView内容失败

时间:2019-03-06 23:11:32

标签: javascript ios swift multithreading wkwebview

我要执行以下操作:

  • 我单击WKWebView中的div元素,然后将消息发送给swift。 - 确定
  • Swift按http请求进行处理以接收json。 - 确定
  • Swift将此json发送到javascript或迅速更改WKWebView DOM- 失败

我的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 );
}

它给我这个错误:

enter image description here

如何快速处理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)
             }
        }
}

没有错误,但也没有任何反应!没用

1 个答案:

答案 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()
}