Swift - 设置应用程序图标的提醒个数(右上角小红圈)

时间:2021-04-20 05:19:11

使用UILocalNotification除了可以实现本地消息的推送功能(可以设置推送内容,推送时间,提示音),还可以设置应用程序右上角的提醒个数。

下面演示如何设置,效果图如下:
Swift - 设置应用程序图标的提醒个数(右上角小红圈)
--- AppDelegate.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import UIKit
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
 
    var window: UIWindow?
 
    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(UIUserNotificationSettings(
            forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
            UIUserNotificationType.Badge, categories: nil))
        return true
    }
 
    func applicationWillResignActive(application: UIApplication) {
    }
 
    func applicationDidEnterBackground(application: UIApplication) {
    }
 
    func applicationWillEnterForeground(application: UIApplication) {
    }
 
    func applicationDidBecomeActive(application: UIApplication) {
    }
 
    func applicationWillTerminate(application: UIApplication) {
    }
}

--- ViewController.swift ---

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import UIKit
 
class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //发送通知消息
        scheduleNotification();
    }
     
    //发送通知消息
    func scheduleNotification(){
        //清除所有本地推送
        UIApplication.sharedApplication().cancelAllLocalNotifications()
         
        //创建UILocalNotification来进行本地消息通知
        var localNotification = UILocalNotification()
        //设置应用程序右上角的提醒个数
        localNotification.applicationIconBadgeNumber = 78;
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}