0

I am trying to add badge to app icon but simply nothing happens.

UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
UIApplication.sharedApplication().applicationIconBadgeNumber = 40;

Do I miss something in this code?

1110
  • 7,829
  • 55
  • 176
  • 334

3 Answers3

5

Did you ask for permission to change badge? This has been changed in iOS8 and require a specific permission:

let settings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge, 
                                        categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
tomsoft
  • 4,448
  • 5
  • 28
  • 35
0

register for remote notification

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

let settings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge, 
                                        categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        return true
    }

Update your badge number

UIApplication.sharedApplication().applicationIconBadgeNumber = 40;
Rohit Kumar
  • 877
  • 6
  • 20
0

Previous answers are old.

iOS 10 and up:

let options: UNAuthorizationOptions = [.alert, .sound, .badge];             
UNUserNotificationCenter.current()(options: options) { (granted, error) in
    //print("granted: \(granted)")
    if let error = error {
        print("Error requestAuthorization: \(error.localizedDescription)")
    }                   
}
Jonny
  • 15,955
  • 18
  • 111
  • 232