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

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

(本文代码已升级至Swift4)

使用 UIApplication.shared.applicationIconBadgeNumber 可以设置应用程序右上角的提醒个数。

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


--- 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
  • 2楼
    2018-09-03 15:56
    yang

    'UIUserNotificationSettings' was deprecated in iOS 10.0: Use UserNotifications Framework's UNNotificationSettings
    站长,过期了就不能通知了吗

    站长回复

    是的,UILocalNotification现在已经被废弃,不能用了。建议使用UserNotifications框架,文章代码现已更新,你可看下。

  • 1楼
    2016-07-08 16:18
    linjoe

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

    站长回复

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

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