23.1 C
London
Tuesday, September 3, 2024

javascript – SwiftUI net view does not present up the primary time


I might like to make use of webview with html and javascript to render one thing. Under is the entire code to breed the issue. I anticipate TestViewPreview to first render textual content “hi there testview”, and after 5 seconds it renders “hello2 testview”. Nevertheless, solely the 2nd one is rendered. For the primary one it provides some error unsure if associated:

evaluateJavaScript: render(‘hi there testview’); TestView.updateUIView
error: Error Area=WKErrorDomain Code=4 “A JavaScript exception
occurred” UserInfo={WKJavaScriptExceptionLineNumber=0,
WKJavaScriptExceptionMessage=TypeError: undefined will not be a perform,
WKJavaScriptExceptionColumnNumber=0, NSLocalizedDescription=A
JavaScript exception occurred}

May you please check out the code beneath?

struct MyState {
  var textual content: String = "abc"
}

struct TestView: UIViewRepresentable {
  let htmlPath: String
  @Binding var state: MyState
  
  func makeUIView(context: Context) -> WKWebView {
    if let htmlPath = Bundle.major.path(forResource: htmlPath, ofType: "html") {
      do {
        let htmlString = attempt String(contentsOfFile: htmlPath)
        WebViewHelper.webView.loadHTMLString(htmlString, baseURL: Bundle.major.bundleURL)
        WebViewHelper.webView.scrollView.showsHorizontalScrollIndicator = true
        print("TestView.makeUIView: Completed inital loading.")
      } catch {
        print("TestView.makeUIView: Error loading HTML file: (error)")
      }
    }
    return WebViewHelper.webView
  }
  
  func updateUIView(_ webView: WKWebView, context: Context) {
    let script = "render('(state.textual content)');"
    print("evaluateJavaScript: (script)")
    webView.evaluateJavaScript(script) { _, error in
      if let error = error {
        print("TestView.updateUIView error: (error)")
      }
    }
  }
}

struct TestViewPreview: View {
  @State personal var state = MyState(textual content: "hi there testview")
  
  var physique: some View {
    TestView(htmlPath: "test_html", state: self.$state)
      .onAppear {
        DispatchQueue.major.asyncAfter(deadline: .now() + 5.0) {
          state.textual content = "hello2 testview"
        }
      }
  }
}

#Preview {
  TestViewPreview()
}

test_html.html

<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
    <meta title="viewport" content material="width=device-width, initial-scale=1.0">
</head>
<physique>
  <div id="output"></div>
  <script>
    perform render(textual content) {
      doc.getElementById("output").innerHTML = textual content
    }
  </script>
</physique>
</html>

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here