何时检查用户是否已登录?

时间:2014-08-27 22:55:29

标签: ios authentication login nsurlconnection

所以我正在开发一个与网络服务器通信的应用程序。该应用程序有一个登录页面,之后显示主要内容(登录时)。 我的问题是,我应该何时检查用户是否在启动应用程序时登录? 目前,我存储了Cookie,并在应用程序启动时发出请求,但请求稍有延迟。这导致登录屏幕可见一秒钟,然后(当收到响应时)视图将分段到内容视图。问题是如果登录,用户不必在开始时查看/等待登录视图。

1 个答案:

答案 0 :(得分:3)

我假设您在登录后有回电。我还假设每个用户都有一个唯一的userID。当用户登录时,您将有一个回调方法,您将在其中显示主页。在您出示之前,请将用户ID保存在NSUserDefaults之类的内容中,

//Assume that an instance of NSDictionary called responseDictionary has the user_id
NSString *userID = [responseDictionary objectForKey:@"user_id"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:userID forKey:@"user_id"];

现在,下次用户启动您的应用时,在(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions文件的AppDelegate.m方法中,恰当地设置rootViewController。这是一个例子。

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
UIViewController *rootViewController;
if([defaults objectForKey:@"user_id"]] != nil) {
   rootViewController = [[HomeViewController alloc]initWithNibName:nil bundle:nil];
}
else {
   rootViewController = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
}
[self.window setRootViewController:rootViewController];

确保在添加注销功能时从默认值中删除userID对象,如下所示:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:@"user_id"];
相关问题