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

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

我完成了一半。我已成功将带有消息的推送通知接收到didReceiveRemoteNotification文件中的AppDelegate.m方法。现在,我需要将其传递给集合 View 所在的 View Controller 。我被困在这一点上。我不知道如何将其发送到 View Controller 。

我尝试在App委托(delegate)中声明一个属性,将消息值分配给它,然后从 View Controller 中引用它,但是它不起作用。我将代表,通知中心,用户默认值绑定(bind)在一起,但没有任何效果。

谁能告诉我如何做到这一点?

谢谢你。

编辑:

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

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:如果您的应用处于前台状态,则会在didReceiveRemoteNotification中收到通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {


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

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

现在,您可以在具有本地通知的任何 Controller 中添加观察者,并执行您想要执行的操作

关于ios - 从推送通知接收的数据从AppDelegate传递到ViewController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22300144/

10-12 00:15
查看更多