UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Alert disappears immediately (because of model change?)

Forums > SwiftUI

@LilaQ  

Hi guys,

I have a View, and a Model - inside the model I load some data, and set a Published variable to true, to show an alert in the view. Something like:

class MyModel: Codable, ObservableObject {
    @Published var showAlert: Bool = false
    ...
      //some network stuff
      showAlert = true
@ObservedObject var mymodel:MyModel
...
.alert(isPresented: $mymodel.showAlert) {
                Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
            }

What happens is, I click my button, all my network stuff runs through, sets the variable to true, and the Alert pops up, but immediately disappears again.

Is this because the model changes and reloads the view or something? I can see the variable being set back to false (which is because the Alert is disappearing I guess). Also, I only have a single Alert in the view. Additionally, I tried the same scenario but with a @State variable local in the View, which worked fine - but I don't know how I would be able to write to this View variable from inside my model functions (I can't pass it as a reference or something, can I?)

I'm pretty new to Swift and SwiftUI, so I hope this question isn't too noobish, and someone can help me out.

Thank you so much in advance!

3      

Is this because the model changes and reloads the view or something?

Could be. Hard to say for sure, though, without seeing more code.

3      

@LilaQ  

It's pretty complex at this point and would probably be huge amounts of code - do you have any idea if / how I could narrow down the cause of this maybe?

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.