How do I stop SwiftUI from reloading WKWebView page that I am using via UIViewRepresentable?

Viewed 867

My code sets the navigation bar title it gets from web page, but everytime this causes the whole WKWebView to reload... The page is quite heavy so consumes a lot of time. Same behaviour when using button to set title.


struct TransitScreen: View, HandlerDelegate {

    var urlRequest: URLRequest
    @State var pageTitle = "Title 1"

    var body: some View {

        VStack {

            KSWebView(urlRequest: urlRequest, delegate: self) // WKWebView using UIViewRepresentable
             
            NavigationLink("Go", destination: Text("Some Data"))
                
            Button(action: {
               pageTitle = "replaced \(Date().toSeconds())"
            }){
               Text("Change title")
            }
            
        }.navigationBarTitle(Text(pageTitle))
        .edgesIgnoringSafeArea(.top)
    }


    func process(data: String){
        pageTitle = data
    }

}

Is there anyway to stop this from happening? or another method to update navigationBarTitle?

1 Answers

Found source of problem

// KSWebView.swift

 func updateUIView(_ uiView: WKWebView, context: Context) {
   uiView.load(urlRequest)
  }

changed this to


func makeUIView(context: Context) -> WKWebView {
        // TODO: Check this hacky code and find some replacement
        let headerHeight = CGFloat(100)
        let webViewHeight = UIScreen.main.bounds.height - headerHeight
        let webViewFrame = CGRect(x: 0, y: headerHeight, width: UIScreen.main.bounds.width, height: webViewHeight)

        let webView = WKWebView(frame: webViewFrame, configuration: config())
        webView.load(urlRequest)
        self.webView = webView
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {

    }

This stops the view from loading request everytime its updated.

Related