Search code examples
iosswiftuiwkwebview

how to change url on web view swiftUI WKWebView


Im really new on iOS swiftui etc. so really I don't know how im doing. But I have a web view loading some web and I need to change the url when willResignActiveNotification and willEnterForegroundNotification and then close de app

I need to call to another html to make the web portal disconection

this is my code

import SwiftUI
import WebKit
struct ContentView: View {
    @State private var urlString: String = "some url"
    
    var body: some View {
        VStack (spacing: 40){
            WebView(url: URL(string: urlString)!)
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
                    
                    exit(0);
                }
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
                    
                    exit(0);
                    }
                }
        
            Spacer()
        }
    }

struct WebView: UIViewRepresentable{
    var url: URL
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    func updateUIView(_ uiView: WKWebView, context: Context){
        let request = URLRequest(url: url)
        uiView.load(request)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I really don't know how to do it


Solution

  • you only have to set the urlString state variable:

    onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        urlString = "https://new_url.com"                
    }
    

    But as Paulw11 mentioned in comment, you should never call exit... it also can be a rejection reason in an App Review. You can rethink your UX and let's say navigate the user to a new screen to show their "logged out" state.