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

Add badge to app icon in iOS 8 with Swift

我想在我的应用程序图标上设置一个徽章,就像在苹果的邮件应用程序中一样(图标顶部的数字)。 我如何在 Swift (iOS8) 中执行此操作?

"number on top of the icon" 称为徽章。徽章可以设置在除应用程序图标之外的许多东西上,包括导航栏工具栏图标。

更改应用程序图标徽章的方法有很多种。大多数用例涉及在应用程序处于后台时设置此项以提醒用户他们可能感兴趣的一些更改。这将涉及推送通知。

有关更多信息,请参阅:https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1

但是,您也可以在应用处于活动状态时更改它。您需要通过注册 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
    }  
}

对于 iOS10Swift 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
  }

2019

答案很简单

UIApplication.shared.applicationIconBadgeNumber = 777

不幸的是,除非您先征求许可,否则它将无法工作

要做到这一点,您只需:

UNUserNotificationCenter.current().requestAuthorization(options: .badge)
     { (granted, error) in
          if error == nil {
              // success!
          }
     }
UIApplication.shared.applicationIconBadgeNumber = NotifCount