如何从AppDelegate打开特定的ViewController?
问题描述:
我知道这个问题已被问了很多次。但我是一个新手,我无法找到任何解决方案来帮助我解决问题。这里有一个简单的解释:如何从AppDelegate打开特定的ViewController?
我有一个应用程序与UITabBarController作为根。
在应用程序委托内部,我检查用户是否已经登录。如果是,我将打开根控制器。
self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
我的应用程序工作正常。但现在我需要实施通知。当我进去didFinishLaunchingWithOptions
通知内容:
NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
NSString *messageType = [notificationPayload objectForKey:@"messageType"];
现在如果有一个消息:
if (messageType.length > 0)
{
//Here based on message I need to open different tabs of TabBarViewController
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
//RootTabBarViewController *listingVC = [[RootTabBarViewController alloc] init];
[(UINavigationController *)self.window.rootViewController pushViewController:tabBarController animated:YES];
}
这段代码上面并没有为我工作。 而且我也不知道如何打开不同的标签,并在这里给他们的徽章形式赋予价值。它总是使用这些代码导航到第一个索引选项卡。我看到其他答案说:
self.tabBarController.selectedIndex = 2;
但没有为我工作。我已经实现了一个UITabBarController
类,我可以从那里为每个标签项徽章设置值,但是我在AppDelegate中获得了我的notificationPayLoad
。
答
正如您所说的,您正在使用TabBarController与故事板。那你为什么要再次初始化?你可以做如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if([[NSUserDefaults standardUserDefaults]boolForKey:@"Selected"])
{
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"Selected"];
UITabBarController *tabController = (UITabBarController*)self.window.rootViewController;
tabController.selectedIndex=1;
}else{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"Selected"];
UITabBarController *tabController = (UITabBarController*)self.window.rootViewController;
tabController.selectedIndex=0;
}
return YES;
}
我在这里只是显示在中didFinishLaunching不同的selectedIndex访问TabbarController演示代码。
答
假设您已经设计了(在故事板中拖动n拖放的UITabBar/UITabBarController)。
if (messageType.length > 0)
{
//Here based on message I need to open different tabs of TabBarViewController
NSUInteger indexOfRequiredTab = 2;// pass the index of controller here
id rootObject = self.window.rootViewController;
if ([rootObject isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabBarControllerObject = (UITabBarController *)rootObject;
if (indexOfRequiredTab != NSNotFound && indexOfRequiredTab < tabBarControllerObject.tabBar.items.count) {
tabBarControllerObject.tabBar.items[indexOfRequiredTab].badgeValue = @"2"; //to set badge value
tabBarControllerObject.selectedIndex = indexOfRequiredTab; //Setting this property changes the selected view controller to the one at the given index in the viewControllers array
}
}
}
查看设计在故事板已经被初始化,我们可以使用IBOutlet
访问它们并改变它们的属性。
试试这个,并修改它为你的情况http://stackoverflow.com/questions/10015567/how-do-i-access-my-viewcontroller-from-my-appdelegate-ios/29773513#29773513 –