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

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

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

下面演示如何设置,效果图如下:


--- AppDelegate.swift ---
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions
        launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //开启通知
        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound],
                                                  categories: nil)
        application.registerUserNotificationSettings(settings)
        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()
        
        //发送通知消息
        scheduleNotification();
    }
    
    //发送通知消息
    func scheduleNotification(){
        //清除所有本地推送
        UIApplication.shared.cancelAllLocalNotifications()
        
        //创建UILocalNotification来进行本地消息通知
        let localNotification = UILocalNotification()
        //设置应用程序右上角的提醒个数
        localNotification.applicationIconBadgeNumber = 78;
        UIApplication.shared.scheduleLocalNotification(localNotification)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
评论1
  • 1楼
    2016-07-08 16:18
    linjoe

    站长,我在AppDelegate添加了那段代码之后报错: No '|' candidates produce the expected contextual result type 'UIUserNotificationType'
    不知道什么问题

    站长回复

    这是因为Swift语法改变造成的,代码现已修正,你再试试看。

    文章太多,后面如果发现哪些有问题的可以给我留言,我都会更新的。