ios - 当应用程序在收到推送通知后变为事件状态时,在主 ViewController 上触发事件

标签 ios objective-c apple-push-notifications

我已成功为我的应用实现推送通知。 我现在想要完成的是从我的 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/

相关文章:

objective-c - 如何知道一个对象是否自动释放?

ios - 强制更新离屏 UICollectionView

ios - 即使里面没有数据,如何设置 UITableViewCell 的自定义背景颜色

ios - Apple 沙箱用户在生产前注销

android - 使用电话设备时,我在 ionic3 中看不到 JSON 数据(来自外部 Url 的 JSON 数据)

ios - 如何使用 Swift 获取推送通知状态?

php - APNS 通知已正确发送但一段时间后未收到。为什么?

ios - 通过应用程序图标启动接收和处理通知 - ios

ios - 无法将 NSData 转换为图片 iphone

ios - 如何获取缓存图像 SDWebImage 的数据