Navigate SwiftUI page from WKWebView operation

2k Views Asked by At

I am a newbie in IOS Programming and also SwiftUI. Coming from Java/Kotlin Android. I want to learn SwiftUI. I have a WKWebView. I want to change SwiftUI page according to url changes in WKWebView. I have done a lot of work as you can see below. But I am struggled in navigation.

struct ContentView: View, Listener {
    func onFetched() {
        NavigationLink(destination: MainView()) {/* HERE this is not working. 
App never goes to MainView.swift page.*/
            Text("Show Detail View")
        }
    }

    var body: some View {
        NavigationView {
            VStack {
                WebView(authListener: self)
            }.navigationBarTitle(Text("PEAKUP Velocity"))
        }
    }
}

struct WebView: UIViewRepresentable {
     var listener: Listener

     @ObservedObject var observe = observable() 

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

    func updateUIView(_ uiView: WKWebView, context: Context) {
         observe.observation = uiView.observe(\WKWebView.url, options: .new) { view, change in
             if let url = view.url {
                self.observe.loggedIn = true     // We loaded the page
                self.listener.onFetched()
                uiView.isHidden = true
            }
        }
        uiView.load("https://google.com")
    }
}

protocol Listener {
    func onFetched()
}

Update: I tried this in onFetched():

 NavigationLink(destination: MainView()) { Text("") }''''

 And I tried this piece of code:
 NavigationView {
        NavigationLink(destination: SecondView()){
            Text("Navigation Link")
        }
    }

Update 2: I tried this code also in onFetched:

self.presentation(Model(MainView(), onDismiss: nil))

Update 3: I tried this:

self.sheet(isPresented: $sayHello) {
        MainView()
    }
1

There are 1 best solutions below

4
On

** Disclaimer I haven't used WKWebviews in the context of SwiftUI, but I assume same would be true. **

I would recommend looking into WKNavigationDelegate. Unless your class is of type WKWebView you need to ensure to assign a delegate to handle any navigation events.

Perhaps you'll find the below article helpful: https://www.hackingwithswift.com/articles/112/the-ultimate-guide-to-wkwebview