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 Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.