这是我的 iOS 场景
1.应用收到远程通知
2.在 Appdelegate 的 didFinishLaunchingWithOptions 我发布一个通知
if let options = launchOptions{
if let remoteNotification = options[UIApplicationLaunchOptionsKey.remoteNotification]{
//post notification
}
}
- 应用的 Root View Controller 是一个导航 Controller ,其根 Controller 是目标 Controller 。
- 在目标 Controller 的 viewDidLoad 中,我添加了一个观察者来获取此通知。
问题是发布通知时未创建目标 View Controller 。所以目标 View Controller 根本得不到通知。如何解决?
最佳答案
您可以将您的通知保存为 AppDelegate 中的引用,例如:
var notification : NSNotifcation?
并在您收到通知时设置它的值。然后在您的 View Controller 中检查 AppDelegate
的 notification
属性是否有值。
if let notification = (UIApplicaton.shared.delegate as! AppDelegate).notification{
// handle your notification
}
另外不要忘记在完成后将 notification
值设置为 nil
。
关于iOS 在 viewcontroller 启动前添加观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40241287/