Add badge to app icon in iOS 8 with Swift Add badge to app icon in iOS 8 with Swift ios ios

Add badge to app icon in iOS 8 with Swift

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:

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


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!          }     }

ericgu's answer seems to be outdated. looks like this -> | got replaced.

Here is a working Swift 2 code:

    let badgeCount: Int = 0    let application = UIApplication.sharedApplication()    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge, .Alert, .Sound], categories: nil))            application.applicationIconBadgeNumber = badgeCount

Edit: Swift 3:

import UIKitimport UserNotificationsclass ViewController: UIViewController {    override func viewDidLoad() {        super.viewDidLoad()        let badgeCount: Int = 10        let application = UIApplication.shared        let center = UNUserNotificationCenter.current()        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in            // Enable or disable features based on authorization.        }        application.registerForRemoteNotifications()        application.applicationIconBadgeNumber = badgeCount    }  }

enter image description here