为了在应用程序加载时而不是在用户登录后显示我的登录屏幕,我决定在用户成功登录时在 NSUserDefaults 中添加一个 auth 对象。当应用程序启动时,检查 auth 参数,并相应地设置视图控制器(如果用户是 auth,它将显示一个提要,如果不是,它将显示一个登录屏幕)在后一种情况下,我有应用程序用户登录后,委托将根视图控制器重置为提要。这是不好的做法还是有更好的方法?
在应用程序委托中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
IIViewDeckController* deckController = [self generateControllerStack];
self.rightController = deckController.rightController;
self.centerController = deckController.centerController;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([[defaults objectForKey:@"auth"] isEqualToNumber:[NSNumber numberWithInt:1]]){
self.window.rootViewController = deckController;
}else{
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard"
bundle:nil];
UIViewController* vc = [sb instantiateViewControllerWithIdentifier:@"loginViewController"];
self.window.rootViewController = vc;
}
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
return YES;
}
- (void) setRoots
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
IIViewDeckController* deckController = [self generateControllerStack];
self.rightController = deckController.rightController;
self.centerController = deckController.centerController;
self.window.rootViewController = deckController;
[self.window makeKeyAndVisible];
}
在登录视图控制器中:
- (IBAction)loginClick:(id)sender {
if([_emailField.text length]>0&&[_passField.text length]>0){
NSString *user = _emailField.text;
NSString *pass = _passField.text;
[[API sharedInstance] login:user andPass:pass onCompletion:^(NSDictionary *json){
NSLog(@"%@", json);
if(![json objectForKey:@"error"]){
[API sharedInstance].authorized = 1;
NSNumber *auth = [NSNumber numberWithInt:1];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:auth forKey:@"auth"];
[defaults synchronize];
captureYouAppDelegate *app = [[UIApplication sharedApplication] delegate];
[app setRoots];
}else{
[API sharedInstance].authorized = 0;
}
}];
}else{
if([_emailField.text length]<1){
[_emailField becomeFirstResponder];
}else{
[_passField becomeFirstResponder];
}
}
}
我想知道是否有比这样做更好或更简单的方法。谢谢!