gpt4 book ai didi

ios - Swift - UNUsernotification 检查 BadgeNumberIcon 中的更改

转载 作者:搜寻专家 更新时间:2023-11-01 06:31:51 28 4
gpt4 key购买 nike

我想在标签中显示角标(Badge)编号的值。

到目前为止,我已将所有内容都放在我的 viewWillAppear 中。因此每次加载 Controller 时都会分配变量。这是代码:

var deliveredNotif = Int()

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
deliveredNotif = UIApplication.shared.applicationIconBadgeNumber
myBadgeLabel.text = "\(deliveredNotif)"
}

我的问题是:如果 Controller 处于事件状态并且已调用 viewWillAppear,我如何更新 deliveredNotif?这意味着如果我在 Controller 中,是否有一种方法可以触发一个函数,它会在每次更改 applicationIconBadgeNumber 的值时更新 deliveredNotif 的值?

谢谢!

--------更新----我的解决方案我创建了一个常量变量:var iconBadgeNumber = NSNumber()

在我的 Appdelegate 中我有:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge])
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "applicationIconBadgeNumber"), object: nil)
iconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
}

然后在我的 Controller 中:

override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateIconBadgeNumber), name: NSNotification.Name(rawValue: "applicationIconBadgeNumber"), object: nil)


}

@objc func updateIconBadgeNumber() {
if iconBadgeNumber == 0 {
print("zero")
} else {
print("there unread notification")
}
}

最佳答案

您可以将您的 UIViewController 设置为关键路径“applicationIconBadgeNumber”的观察者:

首先注册远程通知。在 didFinishLaunchingWithOptions 函数中,添加:

    let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}

不要忘记在文件顶部添加:import UserNotifications

然后在你的viewDidLoad中添加:

UIApplication.shared.addObserver(self, forKeyPath: "applicationIconBadgeNumber", options: .new, context: nil)

然后,覆盖 observeValue 函数:

    override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
if keyPath == "applicationIconBadgeNumber" {
deliveredNotif = UIApplication.shared.applicationIconBadgeNumber
myBadgeLabel.text = "\(deliveredNotif)"
}
}

关于ios - Swift - UNUsernotification 检查 BadgeNumberIcon 中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46281910/

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