我想在标签中显示徽章号码的值。
到目前为止,我已经将所有内容都放到了我的viewWillAppear中。因此,每次加载控制器时,都会对变量进行赋值。代码如下:
var deliveredNotif = Int()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
deliveredNotif = UIApplication.shared.applicationIconBadgeNumber
myBadgeLabel.text = "\(deliveredNotif)"
}我的问题是:如果控制器是活动的,并且viewWillAppear已经被调用,我如何更新deliveredNotif?这意味着,如果我在控制器中,有没有办法触发一个函数,每当applicationIconBadgeNumber的值改变时,它就会更新deliveredNotif的值?
谢谢!
-UPDATE-我的解决方案我创建了一个常量变量:NSNumber iconBadgeNumber = var ()
在我的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")
}
}发布于 2017-09-18 23:28:00
您可以将您的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)"
}
}发布于 2017-09-18 23:11:35
您有3种不同的方法来通知对象某个值已更改:
最后,这篇终极文章将向您解释何时应该使用每一条原则。
KVO vs NSNotification vs protocol/delegates?
在发布一个已经被多次回答的问题之前,你应该尝试进行更认真的调查。
希望这篇文章能对你有所帮助。
https://stackoverflow.com/questions/46281910
复制相似问题