Swift- Remove Push Notification Badge number?
SwiftSwift Problem Overview
I am trying to remove the icon badge in swift, but PFInstallation doesn't seem to work anymore. How do I do this?
Swift Solutions
Solution 1 - Swift
You can "remove" the app badge icon by setting it to 0:
Swift < 3.0
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
Swift 3.0+
UIApplication.shared.applicationIconBadgeNumber = 0
This question shows when you can use it: https://stackoverflow.com/questions/14038680/how-to-clear-push-notification-badge-count-in-ios
Solution 2 - Swift
Swift 4.2
At the AppDelegate, just put this code:
func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
}
Solution 3 - Swift
Swift 5
At the AppDelegate didFinishLaunchingWithOptions
UIApplication.shared.applicationIconBadgeNumber = 0
Solution 4 - Swift
Swift 5
While you can put this in the AppDelegate didFinishLaunchingWithOptions, this will not clear the badge if the app is inactive and has moved to active.
If you wish to clear the badge regardless of the previous state you need to put this in the SceneDelegate instead of the AppDelegate.
func sceneDidBecomeActive(_ scene: UIScene) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
Solution 5 - Swift
A more SwiftUI-oriented approach might be to listen for changes in the @Environment(\.scenePhase) var scenePhase
in the root view. Then, if the new phase is .active
, set UIApplication.shared.applicationIconBadgeNumber
to 0
as discussed by the other answers.
Example Code:
@main
struct MRPApp: App {
@Environment(\.scenePhase) var scenePhase
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
}
}
}