Swift – UNUsernotification检查BadgeNumberIcon中的更改
我想在标签中显示徽章号码的值。
到目前为止,我已经把所有的东西放在了我的视野里。 所以每当控制器加载variables被分配。 代码如下:
var deliveredNotif = Int() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) deliveredNotif = UIApplication.shared.applicationIconBadgeNumber myBadgeLabel.text = "\(deliveredNotif)" }
我的问题是:我如何更新deliverNotif如果控制器是活动的,所以viewWillAppear已被调用? 这意味着如果我在控制器是否有一种方法来触发一个函数,每次更改applicationIconBadgeNumber的值时将更新deliverNotif的值?
谢谢!
——-更新—-我的解决scheme我创build了一个常量variables: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 }
然后在我的控制器中:
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") } }
有三种不同的方式来通知对象有关更改的值:
-
首先你有通知中心,当你的价值改变时通知观察者。 看看这个post ,在互联网上的更多信息,你会发现你想要的。
-
此外,你也可以使用协议和委托,但它似乎只是一个值的通知更新。
-
最后,你一定要看看这个post ,它解释了关键价值观察(KVO)的原理,我相信你已经听说过了。
最后,最后的文章,将解释你什么时候应该使用这个原则。
KVO vs NSNotification vs协议/代表?
在发布已经多次回答的问题之前,您应该尝试进行更严肃的调查。
希望这篇文章能帮助你。
您可以将您的UIViewController
设置为关键path“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)" } }