Reputation: 1278
I want to clear the push notification badge count once app is launched.Im not clear where to set the below code.Please give brief description about clearing the badge count.
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
Upvotes: 43
Views: 48898
Reputation:
Inside ContentView.swift, add the variable:
@Environment(\.scenePhase) var scenePhase
and then add onChange modifier to the outmost stack of your body:
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
print("Active")
}
else if newPhase == .inactive {
UIApplication.shared.applicationIconBadgeNumber = 0
}
else if newPhase == .background {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
Upvotes: 0
Reputation: 71
For iOS 13+
You need to implement either one of these functions in the SceneDelegate.swift file instead of the AppDelegate.swift
func sceneDidBecomeActive(_ scene: UIScene) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
func sceneWillEnterForeground(_ scene: UIScene) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
Think of the AppDelegate as for the App in general, whereas the SceneDelegate is for a specific instance. Better explanation here -> https://stackoverflow.com/a/59965183/7082339
Upvotes: 0
Reputation: 5088
in swift 3+
in your AppDelegate.Swift , when your application active clear all like below.
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
Upvotes: 18
Reputation: 4921
You should set this:
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
in
either of these AppDelegate methods if the application is launched and sent to background then you launch the application didFinishLaunchingWithOptions
method will not be called so use either of these methods:
- (void)applicationWillEnterForeground:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application
For Swift 3+
- func applicationWillEnterForeground(_ application: UIApplication)
- func applicationDidBecomeActive(_ application: UIApplication)
Upvotes: 77
Reputation: 61
UIApplication.shared.applicationIconBadgeNumber = 1
UIApplication.shared.applicationIconBadgeNumber = 0
Upvotes: 0
Reputation: 413
Well, the better way to do this is to make a function that subtract the badge number then make a UIButton to let the user to clear the badge. In the default mail application, if you read one email the badge will subtract one from the icon. You should never set it 0 at launch or resume, it is meaningless and make the app look crappy. Subtract it when the user interact with that event is the best way to do it. Make your app more professional, if you just reset it when the app launch who know what is the bedges mean, may as well not use it.
Upvotes: 2
Reputation: 1120
You can set that code anywhere in code.. Does not matter. But generally, is kept in UIApplicationDidFinishLaunching
..
Upvotes: 1