swiftui – iOS WKWebView exhibits about:clean after app stop and relaunch

0
4
swiftui – iOS WKWebView exhibits about:clean after app stop and relaunch


I am utilizing WKWebView in my iOS app to show an online web page. It really works fantastic when the app is working or backgrounded. Nonetheless, after I stop the app (swipe up) and relaunch it, the WebView solely exhibits about:clean as an alternative of the anticipated URL.

The web site masses simply fantastic after I delete and reinstall the app.

WebView.swift

struct WebView: UIViewRepresentable {
    
    var url: URL?
    
    var redirect: ((URL) -> Void)?
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.isInspectable = true
        webView.navigationDelegate = context.coordinator
        return webView
    }
    
    func updateUIView(_ webView: WKWebView, context: Context) {
        if let url = url {
            webView.load(URLRequest(url: url))
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(mother or father: self)
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        
        var mother or father: WebView
        
        init(mother or father: WebView) {
            self.mother or father = mother or father
        }
    
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            let javascript = """
                if (doc.querySelector('meta[name="viewport"]')) {
                    doc.querySelector('meta[name="viewport"]').setAttribute('content material', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
                } else {
                    const meta = doc.createElement('meta');
                    meta.setAttribute('identify', 'viewport');
                    meta.setAttribute('content material', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
                    doc.getElementsByTagName('head')[0].appendChild(meta);
                }
                true;
            """
            
            webView.evaluateJavaScript(javascript) { consequence, error in
                if let error = error {
                    print("Error injecting JavaScript: (error)")
                } else {
                    print("JavaScript executed efficiently.")
                }
            }
            print("WebView completed loading.")
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            print("WebView failed with error: (error.localizedDescription)")
        }

        func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
            print("WebView provisional load failed: (error.localizedDescription)")
        }
        
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            if let url = navigationAction.request.url, url.scheme == "oauthapp" {
                mother or father.redirect?(url)  // Cross deep hyperlink to your SwiftUI view
                decisionHandler(.cancel) // Cancel navigation
                return
            }
            decisionHandler(.permit)
        }
    }

}

ContentView

func buildAuthURL() -> URL? {
    var parts = URLComponents(string: authURL)
    parts?.queryItems = [
        URLQueryItem(name: "response_type", value: "code"),
        URLQueryItem(name: "client_id", value: clientID),
        URLQueryItem(name: "redirect_uri", value: redirectURI),
        URLQueryItem(name: "code_challenge", value: codeChallenge),
        URLQueryItem(name: "code_challenge_method", value: "S256"),
        URLQueryItem(name: "scope", value: scopes)
    ]
    return parts?.url
}

var physique: some View {
    if accessToken == nil {
        WebView(url: buildAuthURL()){ url in
            if let parts = URLComponents(string: url.absoluteString),
               let code = parts.queryItems?.first(the place: { $0.identify == "code" })?.worth {
                print("Authorization code: (code)")
                authCode = code
                requestAccessToken(code: code)
            } else {
                print("Didn't extract code from URL.")
            }
        }.ignoresSafeArea()
    } else {
        Textual content("Authorization Code: ((authCode ?? "").prefix(15))...")
        Textual content("Entry Token: ((accessToken ?? "").prefix(15))...")
    }
}

What’s occurring:
After quitting and relaunching the app:

  • The WebView seems.
  • But it surely solely exhibits a clean white display screen with about:clean because the URL.

Notes:

  • This solely occurs after a chilly begin (i.e., app was pressure stop).
  • There is not any crash, and every thing else within the app works fantastic.

Query:

How can I be sure that WKWebView correctly masses the supposed URL as an alternative of displaying about:clean after a chilly begin?

LEAVE A REPLY

Please enter your comment!
Please enter your name here