9

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, *) {
    // ?????
}
user4806509
  • 2,925
  • 5
  • 37
  • 72

1 Answers1

5

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
David Seek
  • 16,783
  • 19
  • 105
  • 136
  • Thank you @David Seek . I'll give this a go. – user4806509 Oct 05 '16 at 00:41
  • Thanks @David Seek , haven't yet got around to testing this. I do have another app icon badge type of question with a bounty that you might be able to help solve. http://stackoverflow.com/questions/39922580/voiceover-accessibility-label-and-hint-for-an-app-icon-badge-number – user4806509 Oct 09 '16 at 17:11