我有带有 5 个选项卡的选项卡式应用程序。
应用程序在索引为 0 的选项卡上启动
当我的应用程序收到推送通知时,我想在索引为 1 的选项卡中推送新的视图控制器。
我的代码:
应用委托
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)pushData {
UITabBarController *tabb = (UITabBarController *)self.window.rootViewController;
tabb.selectedIndex = 1;
[[NSNotificationCenter defaultCenter] postNotificationName:@"pushImage" object:@"this is my item id from pushData"];
}
ProfileViewController(标签索引 1)
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushImage:) name:@"pushImage" object:nil];
}
-(void) pushImage: (NSNotification*) notification {
NSString* text = notification.object;
NSLog(@"My id from pushData: %@", text);
}
我的问题是 ProfileViewController 无法响应通知,因为初始化尚未完成,当 AppDelegate 触发通知时。
如果手动打开选项卡 1 并再次切换回选项卡 0,然后发布通知,它会完美响应。所以我需要在标签 1 加载后发布通知,我该如何处理?
我在 TabBarApplication 中从 AppDelegate 推送新 VC 的解决方案
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)pushData {
// ......
if([[pushData objectForKey:@"type"] integerValue] == 0){
// ....
}
else if([[pushData objectForKey:@"type"] integerValue] == 2){
[self handleLikePush:pushData applicationState:application.applicationState];
}
}
-(void)handleLikePush:(NSDictionary *)pushData applicationState:(UIApplicationState) applicationState{
//..
DetailImageViewController *detailImage = [[DetailImageViewController alloc] initWithImageId:imageId];
[self pushViewControllerToCurrentTab:detailImage];
}
}
- (void)pushViewControllerToCurrentTab:(UIViewController *)vc{
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UINavigationController *selectedTabNC = (UINavigationController *)tabBarController.selectedViewController;
if (selectedTabNC != nil) {
[selectedTabNC pushViewController:vc animated:YES];
}
else{
NSLog(@"NavigationController not found");
}
}