Babelfish
Babelfish

Reputation: 135

SwiftUI – Alert is only showing once

I have a strange problem with the SwiftUI Alert view. In an ObservableObject, I do some network requests and in case of a error I will show a alert. This is my simplified model:

class MyModel: ObservableObject {
    let objectWillChange = ObservableObjectPublisher()

    @Published var isError: Bool = false

    public func network() {
        Service.call() {
            self.isError = true

            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }
    }
}

Service.call is a dummy for my network request. My view looks like:

struct MyView: View {
    @ObservedObject var model: MyModel

    var body: some View {
        …
        .alert(isPresented: self.$model.isError) {
            print("Error Alert")
            return Alert(title: Text("Alert"))
        }
    }
}

On the first call, everything works and the alert is shown. For all further calls,print("Error Alert") will be executed and Error Alert appears in the console, but the alert is not shown.

Does anyone have any idea why Alert is only shown once?

Upvotes: 1

Views: 1574

Answers (1)

Asperi
Asperi

Reputation: 257711

Try to use instead (there is already default publisher for @Published properties)

class MyModel: ObservableObject {
    @Published var isError: Bool = false

    public func network() {
        Service.call() {

            DispatchQueue.main.async {
               self.isError = true // << !!! important place to call
           }
        }
    }
}

Upvotes: 2

Related Questions