How to Show Alert from Anywhere in app SwiftUI?

I have condition to show alert in a view which can able to show from anywhere in the app. Like I want to present it from root view so it can possibly display in all view. Currently what happens when I present from very first view it will display that alert until i flow the same Navigation View. Once any sheets open alert is not displayed on it. Have any solutions in SwiftUI to show alert from one place to entire app.
Here is my current Implementation of code. This is my contentView where the sheet is presented and also alert added in it.
Code Block
struct ContentView: View {
@State var showAlert: Bool = false
@State var showSheet: Bool = false
var body: some View {
NavigationView {
Button(action: {
showSheet = true
}, label: {
Text("Show Sheet")
}).padding()
.sheet(isPresented: $showSheet, content: {
SheetView(showAlert: $showAlert)
})
}
.alert(isPresented: $showAlert, content: {
Alert(title: Text("Alert"))
})
}
}
Here from sheet I am toggle the alert and the alert is not displayed.
struct SheetView: View {
@Binding var showAlert: Bool
var body: some View {
Button(action: {
showAlert = true
}, label: {
Text("Show Alert")
})
}
}


here is the error in debug when we toggle button
Code Block
AlertDemo[14187:3947182] [Presentation] Attempt to present <SwiftUI.PlatformAlertController: 0x109009c00> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x103908b50> (from <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x103908b50>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x103d05f50>.

Any solution for that in SwiftUI? Thanks in Advance.
According to the error message, both sheet and alert are implemented as a type of alert controller.
As you know, you cannot show an alert while another alert is already shown.

You may need to close the sheet before showing an alert:
Code Block
struct ContentView: View {
@State var showAlert: Bool = false
@State var showSheet: Bool = false
var body: some View {
NavigationView {
Button(action: {
showSheet = true
}, label: {
Text("Show Sheet")
}).padding()
.sheet(isPresented: $showSheet, content: {
SheetView(showAlert: $showAlert, showSheet: $showSheet)
})
}
.alert(isPresented: $showAlert, content: {
Alert(title: Text("Alert"))
})
}
}
struct SheetView: View {
@Binding var showAlert: Bool
@Binding var showSheet: Bool
@State var showAlertOnDisappear: Bool = false
var body: some View {
Button(action: {
showSheet = false
showAlertOnDisappear = true
}, label: {
Text("Show Alert")
})
.onDisappear {
if showAlertOnDisappear {
showAlert = true
}
}
}
}


Or else, you may need to implement Anywhere-alert in some other ways.
How to Show Alert from Anywhere in app SwiftUI?
 
 
Q