I am in the process of building a Swift app, and am trying to figure out how to display alerts. I have a separate swift file that is doing some calculations, and under a certain conditions I want it to display an alert to the user basically telling them something is wrong. However, most of the examples I have seen require the alert to be within the ContentView
or otherwise somehow connected to a view, and I can't figure out how to display an alert from a separate file outside of any views.
Most of the examples I have seen look something like this:
struct ContentView: View {
@State private var showingAlert = false
var body: some View {
Button("Show Alert") {
showingAlert = true
}
.alert("Important message", isPresented: $showingAlert) {
Button("OK", role: .cancel) { }
}
}}
CodePudding user response:
If I understand your question correctly, you want to show an alert
on the UI when some condition happens in your calculations.
Where the calculations take place somewhere else in your code, eg a task monitoring a sensor.
Here I present an approach, using NotificationCenter
as shown in the example code. Whenever and wherever you are in your code, send a NotificationCenter.default.post...
as in the example code, and the alert will popup.
class SomeClass {
static let showAlertMsg = Notification.Name("ALERT_MSG")
init() {
doCalculations() // simulate showing the alert in 2 secs
}
func doCalculations() {
//.... do calculations
// then send a message to show the alert in the Views "listening" for it
DispatchQueue.main.asyncAfter(deadline: .now() 2) {
NotificationCenter.default.post(name: SomeClass.showAlertMsg, object: nil)
}
}
}
struct ContentView: View {
let calc = SomeClass() // for testing, does not have to be in this View
@State private var showingAlert = false
var body: some View {
Text("calculating...")
.alert("Important message", isPresented: $showingAlert) {
Button("OK", role: .cancel) { }
}
// when receiving the msg from "outside"
.onReceive(NotificationCenter.default.publisher(for: SomeClass.showAlertMsg)) { msg in
self.showingAlert = true // simply change the state of the View
}
}
}