How to load a URL starting with 'https://app.' with with WKWebView?

23 Views Asked by At

I'm trying to load a URL that starts like https://app.example.com into a WKWebView using SwiftUI.

This is not about redirecting to a url. Just need to load the web page https://app.example.com when the View is loaded.

This is my code

struct TestWebView: View {

@State private var isLoading = true
@State private var error: Error? = nil
let url: URL?

var body: some View {
    ZStack {
        if let error = error {
            Text(error.localizedDescription)
                .foregroundColor(.pink)
        } else if let url = url {
            WebView(url: url,
                    isLoading: $isLoading,
                    error: $error)
            .edgesIgnoringSafeArea(.all)
            if isLoading {
                ProgressView()
            }
        } else {
            Text("Sorry, we could not load this url.")
        }
        
    }
}

struct WebView: UIViewRepresentable {
    let url: URL
    @Binding var isLoading: Bool
    @Binding var error: Error?
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    func makeUIView(context: Context) -> WKWebView  {
        let wkwebView = WKWebView()
        wkwebView.navigationDelegate = context.coordinator
        wkwebView.load(URLRequest(url: url))
        return wkwebView
    }
    func updateUIView(_ uiView: WKWebView, context: Context) {
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        var parent: WebView
        init(_ parent: WebView) {
            self.parent = parent
        }
        
        
        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            parent.isLoading = true
        }
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("loading didFinish")
            parent.isLoading = false
        }
        func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
            print("loading error: \(error)")
            parent.isLoading = false
            parent.error = error
        }
        
    }
    
    
}

But it is not loading. No errors either. All other websites are loading properly, eg: google.com, youtube.com etc

Do I have to do anything specific for urls that start with app. ?

Any help would be much appreciated.

0

There are 0 best solutions below