我在哪里放逻辑来加载视图控制器?

时间:2014-09-03 04:23:12

标签: ios objective-c

我的应用启动时:

  • 如果我已登录,我想显示我的主应用程序View Controller
  • 如果我没有登录,我想显示我的应用程序的登录视图控制器

我的故事板上都有两个控制器。

最佳做法是什么?这条逻辑在哪里?

4 个答案:

答案 0 :(得分:3)

以这种方式实现didFinishLaunching方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"LoginView"];

    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"IS_LOGIN"];
    if (isLogin == YES)
    {
        rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"MainHomeView"];
    }
    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];

    return YES;
}

按下登录按钮

时设置为TRUE
- (IBAction)login:(id)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"IS_LOGIN"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    HomeViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainHomeView"];
    AppDelegate *appDelagate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelagate.window.rootViewController = vc;
}

答案 1 :(得分:2)

您必须在AppDelegate.m的{​​{1}}函数

中编写此代码
didFinishLaunchingWithOptions

此处,您必须在用户登录时在 // Check if user is logged in if ([[NSUserDefaults standardUserDefaults] stringForKey:@"loggedIn"] == NULL || [[[NSUserDefaults standardUserDefaults] stringForKey:@"loggedIn"] isEqualToString:@"false"]) { // show login page UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *mainViewController = [storyboard instantiateViewControllerWithIdentifier:@"login"]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.rootViewController = mainViewController; [self.window makeKeyAndVisible]; } else { // show home page UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *mainViewController = [storyboard instantiateViewControllerWithIdentifier:@"home"]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.rootViewController = mainViewController; [self.window makeKeyAndVisible]; } 中设置值。如果用户未登录show loginVC,则为homeVC。

答案 2 :(得分:1)

您可以拥有它,以便登录视图控制器是初始视图控制器。如果他们已登录,那么在viewWillAppear方法中,您可以转到其他视图控制器。

答案 3 :(得分:0)

此逻辑最适合启动viewController(基本上是整个屏幕上有图片的屏幕) 在这个viewController中你检查是否登录,如果是,则执行segue到主应用程序ViewController 否则,登录ViewController

希望这有帮助!