1
votes

I'm trying to hide a splash view when the WKWebView finishes loading. So in my WebView.swift file, I have a coordinater that contains the didFinish delegate. I've put a print statement inside of the didFinish delegate function, but when running the app, I do not see that print statement in my debug console once the webView finishes loading. I've tried using breakpoints aswell, and it makes no difference. Keep in mind that I have no errors showing aswell. Here's my WebView.swift file:

import SwiftUI
import WebKit

struct SwiftUiWebView: UIViewRepresentable {
    
    class Coordinator: NSObject, WKNavigationDelegate {
        let parent: SwiftUiWebView
        
        init(_ parent: SwiftUiWebView) {
            self.parent = parent
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("Done loading")
        }
    }
    
    func makeCoordinator() -> SwiftUiWebView.Coordinator {
        Coordinator(self)
    }
    
    let url: URL?
    
    func makeUIView(context: Context) -> WKWebView {
        let prefs = WKWebpagePreferences()
        prefs.allowsContentJavaScript = true
        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences = prefs
        return WKWebView(frame: .zero, configuration: config)
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        guard let myURL = url else {
            return
        }
       
        let request = URLRequest(url: myURL)
        uiView.load(request)
    }
}

And SwiftUiWebview gets called in ContentView.swift like:

SwiftUiWebView(url: URL(string: "www.mywebsitename.com"))

Does anyone know what I am doing wrong here?

1

1 Answers

3
votes

You need to set the navigation delegate on your WKWebView otherwise it will never be called.

You can do this in the updateUIView call by accessing your coordinator from the context and setting the navigationDelegate to be context.coordinator.

func updateUIView(_ uiView: WKWebView, context: Context) {
    guard let myURL = url else {
        return
    }

    uiView.navigationDelegate = context.coordinator // <- This sets the delegate

    let request = URLRequest(url: myURL)
    uiView.load(request)
}

Once you do that then all navigationDelegate functions should be called if you implement them.