【发布时间】:2015-03-16 15:51:50
【问题描述】:
我想在我的应用程序图标上设置一个徽章,就像在苹果的邮件应用程序中一样(图标顶部的数字)。 如何在 Swift (iOS8) 中做到这一点?
【问题讨论】:
我想在我的应用程序图标上设置一个徽章,就像在苹果的邮件应用程序中一样(图标顶部的数字)。 如何在 Swift (iOS8) 中做到这一点?
【问题讨论】:
UIApplication.shared.applicationIconBadgeNumber = NotifCount
【讨论】:
答案很简单
UIApplication.shared.applicationIconBadgeNumber = 777
很遗憾,除非您事先征得许可,否则它不会起作用。
您只需:
UNUserNotificationCenter.current().requestAuthorization(options: .badge)
{ (granted, error) in
if error == nil {
// success!
}
}
【讨论】:
“图标顶部的数字”称为徽章。除了应用程序图标(包括导航栏工具栏图标)之外,还可以在许多东西上设置徽章。
有很多方法可以更改应用程序图标徽章。大多数用例涉及在应用程序处于后台时设置此设置,以提醒用户他们可能感兴趣的一些更改。这将涉及推送通知。
不过,您也可以在应用处于活动状态时对其进行更改。您需要通过注册 UserNotificationType 来获得用户的许可。获得许可后,您可以将其更改为您想要的任何数字。
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
UIUserNotificationType.Badge, categories: nil
))
application.applicationIconBadgeNumber = 5
【讨论】:
application 是什么?我收到一个错误 (use of unresolved identifier 'application')。
对于 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
}
【讨论】:
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
}
}
【讨论】: