我正在尝试创建一个在首次加载时需要登录的应用程序。用户成功登录后,凭据将存储在钥匙串中,因此用户不必继续登录。
这是我编写的以下代码的快速模型;是否使用AppDelegate
正确的方法来处理首先显示哪个视图?
AppDelegate.h
#import <UIKit/UIKit.h>
#import "KeychainItemWrapper.h"
#import "ViewController.h"
#import "TestBViewController.h"
#import "User.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) TestBViewController *mainVC; // User see's after loggin in
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) KeychainItemWrapper *keychainItem;
- (void)saveKeychainUsername:(NSString *)username andPassword:(NSString *)password;
- (void)loadLoggedInViewControllers;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"AppUniqueID" accessGroup:nil];
// [self.keychainItem resetKeychainItem];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
// Override point for customization after application launch.
NSString *password = [self.keychainItem objectForKey:(__bridge id)(kSecValueData)];
NSString *username = [self.keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];
NSLog(@"username: %@, password: %@", username, password);
if ([username length] <= 0 || [password length] <= 0) {
// Login VC
ViewController *loginVC = (ViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"Login"];
self.window.rootViewController = loginVC;
} else {
[self loadLoggedInViewControllers];
}
return YES;
}
- (void)loadLoggedInViewControllers {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
// Attempt to login user
self.user = [[User alloc] init];
self.user.name = @"Bob";
self.user.hasAccess = YES;
// If user is no longer valid (for whatever reason) remove his keychain information so we can save the new ones.
// Valid user! Skip Login VC
self.mainVC = (TestBViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"Main"];
self.mainVC.user = self.user;
self.window.rootViewController = self.mainVC;
}
ViewController.m - 把它想象成我的 LoginViewController
- (IBAction)storePassButtonTap:(id)sender {
if ([[username text] length] > 0 && [[password text] length] > 0) {
AppDelegate *shareDelegate = [[UIApplication sharedApplication] delegate];
[shareDelegate saveKeychainUsername:[username text] andPassword:[password text]];
[shareDelegate loadLoggedInViewControllers];
} else {
if ([[username text] length] <= 0) {
// Error message
}
if ([[password text] length] <= 0) {
// Error message
}
}
}