如何从 swift 上的 didFinishLaunchingWithOptions 获取 Notificationcenter 数据 4

How to get Notificationcenter data from didFinishLaunchingWithOptions on swift 4

我正在开发一个从远程通知接收数据的应用程序,我试图在打开通过使用 launchOptions 点击通知来应用。问题是我 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")

        }
}

由于您的 application(,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 中生成 post 的部分保留到 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....
}