TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Re-using a WkWebView in multiple SwiftUI views

Forums > SwiftUI

Hi, I am building an app that is a hybrid of SwiftUI and a Single Page Web App (SPA). The SPA will be displayed in a WkWebView, wrapped into SwiftUI using a UIViewRepresentable. It is not always visible, but I can guarantee that only one instance of the web view will be visible at a time.

Since the SPA takes some time to load (due to a heavy JavaScript bundle) and initialize, I'd prefer setting up one single WkWebViews and re-use that whenever SwiftUI needs to display it. I tried this approach, by initializing the WkWebView in a view model and just returning the same instance whenever makeUIView is called in the UIViewRepresentable:

func makeUIView(context: Context) -> WKWebView {
        return viewModel.webView
}

The Coordinator is also constructed when setting up the viewModel. The viewModel itself is initialized in the @main view struct of the app and handed over as using .environment(), so both the webView and the Coordinator are available when SwiftUI shows the web view.

However, this approach causes a crash once the user tries to scroll through the page.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: targetNode'

It seems as if some SwiftUI internals get messed up with this approach.

Is there another way to re-use a single WkWebView across multiple SwiftUI views?

1      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.