Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI application lifecycle

Tags:

ios

swiftui

badge

In my first SwiftUI app, I have Remote Notifications and Background Processes enabled. I did add an AppDelegate class, to support notification.

The notifications set the app badge to an appropriate value.

Since this app has these background modes enabled, several lifecycle events are not working:

  • applicationDidBecomeActive
  • applicationWillResignActive
  • applicationDidEnterBackground
  • applicationWillEnterForeground

Question: where/how do I reset the badge?

like image 565
Sjakelien Avatar asked Mar 22 '26 15:03

Sjakelien


1 Answers

Here is how you can observe didBecomeActiveNotification:

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
                    UIApplication.shared.applicationIconBadgeNumber = 0
                }
        }
    }
}

You can observe other notifications in the same way.


Alternatively you can use an @EnvironmentObject to track the application state:

  • How can I use a method without any page transition or any reboot app
like image 100
pawello2222 Avatar answered Mar 24 '26 09:03

pawello2222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!