Search code examples
iosviewswiftuiswiftui-navigationlink

Open second View like NavigationLink onRecive()


Hello i try to open a new view in the same pattern of the NavigationLink by receiving a notification.

var body: some View {
    return VStack {
        WebView(webPageURL:webPageURL).onReceive(NotificationCenter.default.publisher(for: .viewNotificationMessage)) { notification in

            let message = notification.object as? String ?? ""
            if(message == "Show"){
                //Open her SecoundView like NavigationLink
            }
        }
        NavigationLink(destination: SecoundView()) {
            Text("Do Something")
        }
    }
}

Solution

  • Here it is:

    @State private var isActive = false
    var body: some View {
        return VStack {
            WebView(webPageURL:webPageURL).onReceive(NotificationCenter.default.publisher(for: .viewNotificationMessage)) { notification in
    
                let message = notification.object as? String ?? ""
                if(message == "Show"){
                    self.isActive = true // activate the link below
                }
            }.background(
               NavigationLink(destination: SecoundView(), isActive: $isActive) {
                EmptyView()
            })
        }
    }