Swift - UNUsernotification检查BadgeNumberIcon中的更改

时间:2017-09-18 14:31:46

标签: ios swift notifications

我想在标签中显示徽章编号的值。

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

var deliveredNotif = Int()

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

我的问题是: 如果控制器处于活动状态并且已经调用了viewWillAppear,我如何更新deliverNotif?意思是如果我在控制器中是否有一种方法可以触发一个func,每次更改applicationIconBadgeNumber的值时都会更新deliverNotif的值?

谢谢!

-------更新----我的解决方案 我创建了一个常量变量: 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")
    }
}

2 个答案:

答案 0 :(得分:2)

您可以将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)"
        }
    }

答案 1 :(得分:1)

您有3种不同的方式来通知对象有关更改的值:

  • 首先,您拥有通知中心,以便在您的值发生变化时通知观察者。 查看此post以及互联网上的更多信息,您将找到所需内容。

  • 此外,您还可以使用协议和委托,但只是对某个值的通知更新似乎很重。

  • 最后你一定要看看这个post,它解释了键值观察(KVO)的原理,我相信你已经听说过了。

最后,最终的文章将解释你何时应该使用这一原则。

KVO vs NSNotification vs protocol/delegates?

在发布已经多次回答的问题之前,您应该更加认真地进行调查。

希望这篇文章能为您提供帮助。