How to set an app icon badge number in iOS 10?

user4806509 picture user4806509 · Oct 5, 2016 · Viewed 17.2k times · Source

Problem:

I am trying to set an app icon badge number in iOS 10, however it is failing. I understand UIUserNotificationSettings is now deprecated in iOS and UNNotificationSettings replaces it.

Question:

How do I modify the below code to use UNNotificationSettings to update the icon badge number in iOS 10? Or is there another concise method?

Code:

The following code shows how I set badges from iOS 7 - iOS 9.

let badgeCount: Int = 123
let application = UIApplication.sharedApplication()

if #available(iOS 7.0, *) {
    application.applicationIconBadgeNumber = badgeCount
}

if #available(iOS 8.0, *) {
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil))
    application.applicationIconBadgeNumber = badgeCount
}

if #available(iOS 9.0, *) {
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil))
    application.applicationIconBadgeNumber = badgeCount
}

if #available(iOS 10.0, *) {
    // ?????
}

Answer

David Seek picture David Seek · Oct 5, 2016

You need to implement UserNotifications into AppDelegate.

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

And then use the following code within didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        if error != nil {
            //
        }
    }
    return true

}

Here you can find tons of important stuff on the notifications topic.

For the badge:

let content = UNMutableNotificationContent()
content.badge = 10 // your badge count