7

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?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Sjakelien
  • 2,255
  • 3
  • 25
  • 43

2 Answers2

13

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:

pawello2222
  • 46,897
  • 22
  • 145
  • 209
3
@Environment (\.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onChange(of: scenePhase) { newPhase in
                    if newPhase == .active {
                        UIApplication.shared.applicationIconBadgeNumber = 0
                    }
            }
        }
    }
kAiN
  • 2,559
  • 1
  • 26
  • 54
  • Correct, but better explained here: https://stackoverflow.com/questions/63818327/determine-background-status-with-swiftui – Oded Ben Dov Apr 30 '23 at 05:40