当接收推送通知(didReceiveRemoteNotification)时,如何将通知处理从应用程序委托(delegate)传递到 View Controller ? 这对于在 View 上显示警报非常有用。释放 View 或其他相关内容。
AppDelegate.m 的伪代码示例:
- (void)application:(UIApplication*)application didReceiveRemoteNotification (NSDictionary*)userInfo{
NSLog(@"Received notification: %@", userInfo);
// Here send the userInfo or other data to the appropriate view controller for handling it there (for example showing an alert there) //
}
最佳答案
确实没有理由在应用程序中传递 didReceiveNotification。它的目的是处理一次;话虽这么说,我相当不确定您为什么要传递委托(delegate)。
如果你想将 View Controller 置于其他一切之上(我对你的 View 层次结构一无所知,所以我不知道这是否真的是你会使用的东西),你也许可以这样做:
[[self.window rootViewController] presentViewController:[[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil] animated:YES completion:^{}];
这段代码只是在所有内容之上抛出一个模态视图。
或者,如果由于某种原因,您确实需要在更多位置处理通知,而不仅仅是应用程序委托(delegate),则您可以执行以下两件事:
委托(delegate)模型
在 AppDelegate header 中创建一个新的委托(delegate)协议(protocol),并将其设置为您想要的任何处理程序 - 这样做的缺点是(如上所述)是一次只有一个对象可以监听委托(delegate)
@protocol MyNotificationDelegate <NSObject>
@required
-(void) applicationDidReceiveRemoteNotification: (NSDictionary*)userInfo;
@end
发布通知
任意多个对象都可以监听此通知;在你想听的对象中:
AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"ReceivedNotification" object:appDel];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived:) name:@"ReceivedNotification" object:appDel];
并添加功能:
-(void)notificationReceived :(NSNotification *)localNot{
NSLog(@"userInfo from push: %@",localNot.userInfo );
}
在您的应用程序委托(delegate)回调中:
- (void)application:(UIApplication*)application didReceiveRemoteNotification: (NSDictionary*)userInfo{
NSLog(@"Received notification: %@", userInfo);
[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedNotification" object:self userInfo:userInfo];
}
关于ios - 如何处理 View Controller 上的远程通知(而不是 AppDelegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977377/