无法在 IOS 中更改应用徽章

Can't change app badge in IOS

我正在尝试将徽章添加到应用程序图标,但没有任何反应。

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

我是否遗漏了这段代码中的某些内容?

您是否请求允许更改徽章?这已在 iOS8 中更改并需要特定权限:

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

注册远程通知

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

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

更新您的徽章编号

UIApplication.sharedApplication().applicationIconBadgeNumber = 40;

以前的答案是旧的。

iOS 10 岁及以上:

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)")
    }                   
}