使用Swift将徽章添加到iOS 8中的应用程序图标

我想在我的应用程序的图标上设置一个徽章,就像在苹果的邮件应用程序(图标顶部的数字)一样。 我怎么能在Swift(iOS8)中做到这一点?

“图标顶部的数字”称为徽章。 除了应用程序图标(包括导航栏工具栏图标)外,徽章还可以设置在许多其他项目上。

有许多方法来更改应用程序图标徽章。 大多数使用情况都是在应用程序处于后台时提醒用户,他们可能会感兴趣的某些更改将会涉及到推送通知。

有关更多信息,请参阅: https : //developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html

但是,您也可以在应用程序处于活动状态时对其进行更改。 您将需要通过注册UserNotificationType来获得用户的许可。 一旦获得许可,您可以将其更改为任何您希望的号码。

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil )) application.applicationIconBadgeNumber = 5 

在这里输入图像说明

ericgu的答案似乎已经过时了。 看起来像这样 – > | 被取代。

这里是一个工作的Swift 2代码:

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

编辑: Swift 3:

 import UIKit import UserNotifications class 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 } } 

在这里输入图像说明

对于iOS10向后兼容的 Swift 3 ,你可以把最好的答案包装成一个很好的(静态的)实用程序函数:

 class func setBadgeIndicator(badgeCount: Int) { let application = UIApplication.shared if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.badge, .alert, .sound]) { _, _ in } } else { application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)) } application.registerForRemoteNotifications() application.applicationIconBadgeNumber = badgeCount }