1

我正在开发一个从远程通知接收数据的应用程序,我试图在通过点击通知打开应用程序时将该数据传递didFinishLaunchingWithOptions给我的ViewController使用。问题是我的观察者没有得到任何数据。NotificationcenterlaunchOptionsviewDidAppear

这是我的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")

        }
}
4

1 回答 1

2

由于您的 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 中已有的部分,该部分在收到远程通知时生成到 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....
}
于 2018-08-16T11:08:52.270 回答