Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add badge to app icon in iOS 8 with Swift

I'd like to set a badge on the icon of my app like in apple's mail app (number on top of the icon). How can I do this in Swift (iOS8)?

like image 932
hans Avatar asked Jan 18 '15 15:01

hans


People also ask

How do I put notification badges on icons?

Turn on App icon badges from Settings. Navigate back to the main Settings screen, tap Notifications, and then tap Advanced settings. Tap the switch next to App icon badges to turn them on.


2 Answers

The "number on top of the icon" is called a Badge. Badges can be set on a number of things besides Application Icons including Navigation Bar toolbar icons.

There are many ways to change the Application Icon Badge. Most use cases involve setting this when the Application is in the background to alert the user that there is some change that they may be interested in. This would involve a push notification.

For more on that see: https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1

However, you can also change it while your app is active. You will need permission from the user by registering the UserNotificationType. Once you get permission, you can change it to whatever number you wish.

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |         UIUserNotificationType.Badge, categories: nil         ))  application.applicationIconBadgeNumber = 5 

enter image description here

like image 151
ericgu Avatar answered Sep 22 '22 22:09

ericgu


2019

The answer is simply

UIApplication.shared.applicationIconBadgeNumber = 777 

Unfortunately though it will not work unless you ask for permission first.

To do that you simply:

UNUserNotificationCenter.current().requestAuthorization(options: .badge)      { (granted, error) in           if error == nil {               // success!           }      } 
like image 38
Fattie Avatar answered Sep 21 '22 22:09

Fattie