在我的应用程序中,有一个 Collection View 显示一组从网络服务检索到的图像。每个图像都有标签。因此,该应用程序还可以使用标签过滤图像。
现在我正在尝试向此应用程序添加推送通知。将新图像添加到服务器时会发送推送通知。这些图像被标记为最新。我通过推送通知将该标签作为消息传递,我需要的是当用户点击推送通知打开应用程序时,它应该将最新的新图像加载到 Collection View 中。
我已经完成了一半。我收到推送通知,消息成功发送到 AppDelegate.m
文件中的 didReceiveRemoteNotification
方法。现在我需要将它传递给 Collection 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; }
Case2:如果你的应用在前台,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/