gpt4 book ai didi

ios - 根据通知数量增加角标(Badge)值

转载 作者:行者123 更新时间:2023-11-28 11:47:52 25 4
gpt4 key购买 nike

我在我的应用程序中显示通知,但我无法根据通知数量增加角标(Badge)编号。我的代码如下:

func notifcation(model: Model) -> Void {
let calendar = Calendar.current
guard let date = model.remiderDate else {return}
let title = model.name
let body = model.desc
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default()
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber

let identifier = "\(date)"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)


center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print(error as Any)
}
})
}

我能够收到多个通知,但无法增加角标(Badge)值以反射(reflect)通知数量。

如果应用程序当前正在运行,应用程序通知也不会显示,但如果应用程序在后台,则通知有效。

最佳答案

你可以使用这个增加角标(Badge):

UIApplication.shared.applicationIconBadgeNumber += 1

或者:

content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)

要在应用程序处于前台时接收通知,您的 View Controller 应符合 UNUserNotificationCenterDelegate 协议(protocol)并实现 userNotification:willPresent 方法,然后声明您的 View Controller 作为 viewDidLoad() 中的通知委托(delegate):

class ViewController: UIViewController, UNUserNotificationCenterDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//...
UNUserNotificationCenter.current().delegate = self
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
}

有关本地通知的更多信息,请查看 here .

关于ios - 根据通知数量增加角标(Badge)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52239313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com