如何在iOS 10中设置应用图标徽章编号?

use*_*509 7 optimization notifications badge ios swift

问题:

我试图在iOS 10中设置应用程序图标徽章编号,但它失败了.据我所知UIUserNotificationSettings,iOS现已弃用并UNNotificationSettings取而代之.

题:

如何修改以下代码以用于UNNotificationSettings更新iOS 10中的图标徽章编号?还是有另一种简洁的方法吗?

码:

以下代码显示了我如何设置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, *) {
    // ?????
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*eek 5

您需要实现UserNotificationsAppDelegate.

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
Run Code Online (Sandbox Code Playgroud)

然后在以下代码中使用以下代码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

}
Run Code Online (Sandbox Code Playgroud)

在这里,您可以在通知主题上找到大量重要内容.

对于徽章:

let content = UNMutableNotificationContent()
content.badge = 10 // your badge count
Run Code Online (Sandbox Code Playgroud)