我已成功为我的应用实现推送通知。
我现在想要完成的是从我的 AppDelegate
向根 ViewController
发送某种标志,以防应用程序收到 PN。
我首先检查 applicationDidBecomeActive:
中的角标(Badge)编号,如下所示:
if (application.applicationIconBadgeNumber>0) {
self.hasNotification = YES;
NSLog(@"APNs Message received");
}
现在,我不确定如何将此消息传达给我的根 ViewController
以便触发将用户带到其中一个 View 的 segue。解决这个问题的最佳方法是什么?
最佳答案
鉴于许多 View Controller 可能对此事件感兴趣,这听起来像是使用 NSNotifications 提供的发布/订阅模型的良好候选者。
发布通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyEventName" object:optionalPayload];
订阅通知:
- (void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:)
name:@"MyEventName" object:nil];
}
- (void)dealloc
{
//Unsubscribe yourself in dealloc
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)handleNotification:(NSNotification *)pNotification
{
NSLog(@"#1 received message = %@",(NSString*)[pNotification object]);
//Perform your segue here
}
替代方案:自定义根 VC
如果您已创建自己的特定于域的容器 View Controller 作为 Root View Controller ,则可以执行以下操作:
- 将事件发送到 Root View Controller 。
- Root View Controller 将询问其当前的 subview 是否对该事件感兴趣(可能通过标记协议(protocol)),并传播它。
我几乎总是在我的应用程序中使用自定义容器 - RootViewController,因为它可以生成清晰易读的代码,准确描述正在发生的情况。不仅如此,它还使得从这里实现核心布局内容(例如滑动菜单等)变得非常简单。
关于ios - 当应用程序在收到推送通知后变为事件状态时,在主 ViewController 上触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19723318/