iosswiftuigrand-central-dispatchdispatch-queue

SwiftUI toasts not Dismissing


I am using the following method to display a toast message

DispatchQueue.main.async {
Toastmessage = MyToasts(title: "Message Here" , type: .success)
mysettings.showMytoast = true // mysettings is an Environment variable
}

Reason I added like this because toast occurs as result of an action (Removing an item from list) and there is a delay to update view from response.

Now the issue is toast is not getting dismissed until i kill the app. Any solution for this?


Solution

  • I think you should showMyToast = false after a while.

    You can do something like:

    DispatchQueue.main.async {
        Toastmessage = MyToasts(title: "Message Here" , type: .success)
        mysettings.showMytoast = true // mysettings is an Environment variable
        
        let closeAfterSecond = 1
        DispatchQueue.main.asyncAfter(deadline: .now() + closeAfterSecond) {
            mysettings.showMytoast = false
        }
    }