我想在我的应用图标上设置徽章,就像在Apple的邮件应用程序中一样(图标顶部的数字)。 我怎么能在Swift(iOS8)中做到这一点?
答案 0 :(得分:29)
图标顶部的"数字"被称为徽章。除了应用程序图标(包括导航栏工具栏图标)之外,还可以在许多项目上设置徽章。
有很多方法可以更改应用程序图标徽章。大多数用例涉及在应用程序处于后台时设置此项以提醒用户他们可能感兴趣的某些更改。这将涉及推送通知。
但是,您也可以在应用处于活动状态时进行更改。您需要通过注册UserNotificationType来获得用户的许可。获得许可后,您可以将其更改为您希望的任何数字。
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
UIUserNotificationType.Badge, categories: nil
))
application.applicationIconBadgeNumber = 5
答案 1 :(得分:18)
这是一个有效的 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
}
}
答案 2 :(得分:11)
对于 iOS10 , Swift 3 以及向后兼容性,您可以将最佳答案包装到一个漂亮的(静态)实用程序函数中:< / p>
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
}
答案 3 :(得分:6)
答案很简单
void main() {
test('startLoadingQuizReducer sets isLoading true', () {
var initState = QuizGameState(null, null, null, false);
var expectedState = QuizGameState(null, null, null, true);
var action = StartLoadingQuiz();
var actualState = quizGameReducer(initState, action);
// my test fails here
expect(actualState, expectedState);
});
不幸的是,除非您先征得许可,否则它不起作用。
要做到这一点,您只需:
UIApplication.shared.applicationIconBadgeNumber = 777
答案 4 :(得分:0)
UIApplication.shared.applicationIconBadgeNumber = NotifCount