[英]How to get Notificationcenter data from didFinishLaunchingWithOptions on swift 4
我正在开发一个从远程通知中接收数据的应用程序,当通过使用launchOptions
轻按Notificationcenter
打开应用程序时,我正在尝试使用Notificationcenter
将数据从didFinishLaunchingWithOptions
传递至ViewController
。 问题是我的viewDidAppear
上的观察者没有获取任何数据。
这是我在didFinishLaunchingWithOptions
方法上的代码:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable : Any] {
let nameSchool = remoteNotification["name_school" as! String]
NotificationCenter.default.post(name: Notification.Name.nameSchool, object: nameSchool)
}
}
观察者在viewDidAppear
方法中:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(forName: Notification.Name.nameSchool, object: nil, queue: OperationQueue.main) { (nameSchool) in
let schoolName = nameSchool.object as! String
self.messagePopup(message: "Data received")
}
}
由于您的应用程序(,didFinishLaunchingWithOptions :)将在viewDidAppear之前(根据您的评论)被调用,因此您将必须临时存储从函数中获得的结果,直到您的代码以后可以检索它为止。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var remoteNotificationAtLaunch: [AnyHashable: Any]?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.remoteNotificationAtLaunch = launchOptions?[.remoteNotification] as? [AnyHashable : Any]
}
...
}
显然,在收到远程通知时,将您已经拥有的部件保留在AppDelegate中,该部件会在NotificationCenter中生成帖子。 然后在您的视图控制器中,更新viewDidAppear ...
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
observeNotifications()
checkForNotificationAtLaunch()
}
private func observeNotifications() {
NotificationCenter.default.addObserver(forName: Notification.Name.nameSchool, object: nil, queue: OperationQueue.main) { (nameSchool) in
let schoolName = nameSchool.object as! String
self.processNotification(schoolName: schoolName)
}
}
private func checkForNotificationAtLaunch() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let notificationAtLaunch = appDelegate.remoteNotificationAtLaunch,
let schoolName = notificationAtLaunch["name_school"] as? String {
processNotification(schoolName: schoolName)
}
}
}
private func processNotification(schoolName: String) {
self.messagePopup(message: "data received")
// do something with schoolName....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.