Monday, June 10, 2024
HomeiOS Developmentjavascript - SwiftUI internet view would not present up the primary time

javascript – SwiftUI internet view would not present up the primary time


I would 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 “whats up testview”, and after 5 seconds it renders “hello2 testview”. Nevertheless, solely the 2nd one is rendered. For the primary one it provides some error undecided if associated:

evaluateJavaScript: render(‘whats up testview’); TestView.updateUIView
error: Error Area=WKErrorDomain Code=4 “A JavaScript exception
occurred” UserInfo={WKJavaScriptExceptionLineNumber=0,
WKJavaScriptExceptionMessage=TypeError: undefined just isn’t 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 = strive 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: "whats up 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>



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments