Swift - 设置应用程序图标的提醒个数(右上角小红圈)
作者:hangge | 2015-07-22 10:20
(本文代码已升级至Swift4)
下面演示如何设置,效果图如下:

--- AppDelegate.swift ---
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//请求通知权限
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
(accepted, error) in
if !accepted {
print("用户不允许消息通知。")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
--- ViewController.swift ---
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//设置应用程序右上角的提醒个数
UIApplication.shared.applicationIconBadgeNumber = 78
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
全部评论(2)
'UIUserNotificationSettings' was deprecated in iOS 10.0: Use UserNotifications Framework's UNNotificationSettings
站长,过期了就不能通知了吗
站长回复:是的,UILocalNotification现在已经被废弃,不能用了。建议使用UserNotifications框架,文章代码现已更新,你可看下。
站长,我在AppDelegate添加了那段代码之后报错: No '|' candidates produce the expected contextual result type 'UIUserNotificationType'
不知道什么问题
站长回复:这是因为Swift语法改变造成的,代码现已修正,你再试试看。