[英]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.