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

WebView turns blank when in background

Forums > SwiftUI

@Arban  

Having some issues with a webview that turns blank when app is in background for a while. I want the webview to reload if it has been terminated when the app returns to foreground.

The structure of the webview is basically like this:

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {

    func makeUIView(context: Context) -> WKWebView {
            let webView = WKWebView()
            return webView
        }

    func updateUIView(_ webView: WKWebView, context: Context) {
        let html = "<html><body>Hello World!</body></html>"
        let baseUrlWk = Bundle.main.bundleURL
        webView.loadHTMLString(html, baseURL: baseUrlWk)
    }
}

I've tried to implement a reload with WebContentProcessDidTerminate - and it actually solved the problem but also has some unwanted side effects. The webview reload seems to trigger on many things - e.g. when a sheet is presented without any State-variable being changed. Very disturbing...

import SwiftUI
import WebKit

class WebViewNavigationDelegate: NSObject, WKNavigationDelegate {
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        webView.reload()
    }
}

struct WebView: UIViewRepresentable {

    private let navigationDelegate = WebViewNavigationDelegate()

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = navigationDelegate 
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        let html = "<html><body>Hello World!</body></html>"
        let baseUrlWk = Bundle.main.bundleURL
        webView.loadHTMLString(html, baseURL: baseUrlWk)
    }
}

How can I implement the webViewNavigationDelegate without having the unwanted side effects?

2      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.