繁体   English   中英

将从推送通知接收的数据从AppDelegate传递到ViewController

[英]Passing data received from a push notification from the AppDelegate to a ViewController

在我的应用程序中,有一个集合视图,显示从Web服务检索的一组图像。 每个图像都有标签。 因此,该应用程序还可以使用标签过滤图像。

现在我正在尝试向此应用添加推送通知。 将新图像添加到服务器时会发送推送通知。 这些图像标记为最新 我通过推送通知将该标记作为消息传递,我需要的是当用户点击推送通知以打开应用程序时,它应该将最新的新图像加载到集合视图中。

我已经完成了一半。 我收到推送通知与消息成功到didReceiveRemoteNotification的方法AppDelegate.m文件。 现在我需要将它传递给集合视图所在的视图控制器。 我陷入了困境。 我无法弄清楚如何将其发送到视图控制器。

我尝试在App委托中声明一个属性,为它分配消息值并从视图控制器中引用它,但它不起作用。 我绑定了代表,通知中心,用户默认值但没有任何效果。

任何人都可以告诉我如何做到这一点?

谢谢。

编辑:

这是我的代码。 我尝试的最后一种方法是本地通知。

AppDelegate.m

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PushNotificationMessageReceivedNotification" object:nil userInfo:userInfo];
}

ViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(remoteNotificationReceived:) name:@"PushNotificationMessageReceivedNotification"
                                               object:nil];
}

- (void)remoteNotificationReceived:(NSNotification *)notification
{
    NSLog(@"Notification: %@", notification.userInfo);
    NSString *msg = [[notification.userInfo valueForKey:@"aps"] valueForKey:@"alert"];
    self.label.text = msg;
}

案例1:如果您的应用程序是后台并且用户启动带有通知的应用程序,那么您可以检查应用程序是通过通知还是正常启动的

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];


        NSDictionary *remoteNotificationPayload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (remoteNotificationPayload) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:remoteNotificationPayload];
       }
return YES; }

案例2:如果您的应用程序处于forground通知,则会在didReceiveRemoteNotification中收到

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {


    NSLog(@"userinfo %@",userInfo);

    [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:userInfo];
}

现在,您可以在任何带有本地通知的控制器中添加一个观察者,并执行您想要做的事情

我不知道它会起作用,它只是我的建议。 我以前没有尝试过,但在你的情况下可能是用户NSUserDefaults为此工作。

在你的appDelegate.m中

[[NSUserDefaults standardUserDefaults] setObject:imageArrayFromServer forKey:@"MyAppSpecificGloballyUniqueString"];

在你的viewController.m中

NSArray *myArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAppSpecificGloballyUniqueString"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM