I have a main tab bar that has three tabs, in the first tab I have a background task that may return an error, this error is presented by an alert view. now if I moved to any tab views in the app while the background task is running and an error occurred the alert will present on the current view instead of showing in the first tab view.
struct FirstTabView: View {
// viewModel will fire the background task after init
@StateObject var viewModel: FirstViewModel = .init()
var body: some View {
Text("Hello First")
.alert("error", isPresented: .init(get: {
return viewModel.errorMessage != nil
}, set: { _ in
viewModel.errorMessage = nil
})) {
Button("OK") {
}
}
}
}
how can I limit the error alert to be presented on the first tab only?
2
Answers
One solution could be move the alert to the main
TabView
, rather than having it shown in the child view. By doing that, you will be able to track what tab is selected and trigger the alert only when both conditions are true:errorMessage
is not nilThe trigger is a dedicated
showAlert
state property in yourTabView
view, that will change whenever the first tab appears on the screen.In the example here below, you can change your view-model’s property from the second view, but the alert will only be shown when you move to the first tab; I hope this is what you are looking for:
One way to handle it is by updating the badge icon on the first tab when the error occurs. Then the user can finish off what they are currently doing and then inspect the first tab when they notice it has updated, say with an exclamation mark badge. At that point, you could present the alert.