远程推送通知在另一个视图控制器中接收

时间:2015-02-19 23:22:06

标签: ios push-notification apple-push-notifications

我是iOS开发的新手,我在理解如何确保视图控制器获得推送通知方面遇到一些麻烦,无论视图是否打开。

基本上,我想要的是使用推送通知消息更新视图控制器界面。

我有一个设置如下的故事板:

导航控制器 - >视图控制器1 - >视图控制器2 - >查看控制器3

我希望View Controller 3得到更新。但是,在我的应用程序委托中 - 它接收远程通知。所以,它知道消息是什么。

我尝试了几件事情,只有当视图控制器位于前台并且用户正在查看该视图时,我才能让View Controller 3更新。

但是,如果用户在View Controller 1上 - 那么当我收到推送通知并且我转到View Controller 3时 - 它不会更新数据。

我唯一的假设是视图控制器3已被解除分配,因为视图尚未加载。因此,它无法收听通知。如何让View Controller 3监听远程通知?我是否必须在我的app委托文件中对它进行某种引用?如果是这样,我该如何设置?

在我的app委托文件中,方法:didReceiveRemoteNotification:

[[NSNotificationCenter defaultCenter] postNotificationName:messageNotificationName object:nil userInfo:userInfo];    

在我的View Controller 3,viewDidLoad方法中,我注册了通知:

// register to find out when push notifications are received.
NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
                       selector:@selector(notificationRecieved:)
                           name:messageNotificationName
                         object:nil];     

目前,我还没有注册通知 - b / c我希望它即使在视图未加载时也能收到它。

非常感谢任何帮助或建议。

我一直在阅读Apple本地和远程通知指南。 我还研究了一个关于stackoverflow的TON,试图找到一些可以帮助我并指出正确方向的东西。

我还为didFinishLaunchingWithOptions编写了一些代码,以防万一从通知中打开应用程序。

    NSDictionary *notif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

//Accept push notification when app is not open
if (notif) {
    // Extract the payload
    NSDictionary *tempDict = [notif valueForKey:@"aps"];

    [[NSNotificationCenter defaultCenter] postNotificationName:messageNotificationName object:nil userInfo:tempDict];


    UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;

    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

    ViewController3 *controller = (ViewController3*)[mainStoryboard instantiateViewControllerWithIdentifier: @"ViewController3"];

    [navigationController pushViewController:controller animated:YES];
}

1 个答案:

答案 0 :(得分:1)

好像您在实例化ViewController3之前发布通知一样。如果在发布通知时设置断点并设置通知侦听器,则会注意到在通知触发后设置了侦听器。

从架构上讲,你可能根本就没有通知。只需更新您的数据模型,然后ViewController3利用您的数据模型填充其视图。