LoginSignup
33
33

More than 5 years have passed since last update.

ログイン状態とかで最初の画面を変えたりするやつ

Last updated at Posted at 2014-04-02

例えば、UserDefaultsとかに何かしらの情報を持っているかいないかでアプリを立ち上げた時に表示する画面を変えたい。そんな時のやつ。
これよりもっと良いやり方もあるのかもしれないけど覚えたてのコードを備忘録として記録しておく。

Storyboardの設定(ざっくり)

test_—_Main_storyboard_—_Edited.png

まずAppDelegateでゴニョゴニョする

tokenってのが保存されているかで画面を変えるって場合。
これを書いておけば多分切り替わる。

AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>
// ここはこれがいいのかどうなのかはわからない(写経しただけ
@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m

ストーリーボードの名前が「Main」だったとして。

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        UIViewController *viewController = [[UIViewController alloc] init];

        // ここでtokenとかを取ってくる
        // UserDefaultsの場合
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *token = [userDefaults objectForKey:@"token"];

        if (token == nil) {
                viewController = [storyBoard instantiateViewControllerWithIdentifier:@"NG"];
        } else {
                viewController = [storyBoard instantiateViewControllerWithIdentifier:@"OK"];
        }

        // ここも写経しただけ
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        self.window.rootViewController = viewController;
        [self.window makeKeyAndVisible];

        return YES;
}

ログインした時

APIか何かを使って認証に成功したらログイン後の画面を表示したい。

ログインに成功したらこう!

LogoutView *logoutView =  [self.storyboard instantiateViewControllerWithIdentifier:@"OK"];
[self presentViewController:logoutView animated:YES completion:nil];

ログアウトしたいとき

ログアウトのボタンをタップした時はこう!!

LoginView *loginView = [self.storyboard instantiateViewControllerWithIdentifier:@"NG"];
[self presentViewController:loginView animated:YES completion:nil];

(編集履歴消せないのかな)

33
33
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
33