2014-08-27 95 views
2

因此,我正在开发一个与Web服务器通信的应用程序。该应用程序有一个登录页面,之后显示主要内容(登录时)。 我的问题是我应该在应用程序启动时检查用户是否登录? 目前,我正在存储Cookie,并在应用程序开始时提出请求,但请求有轻微延迟。这会导致登录屏幕显示一秒钟,然后(当收到响应时)视图停留在内容视图中。问题是,如果登录,用户不必在开始时看到/等待登录视图。何时检查用户是否已登录?

回答

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"]; 

现在,下一次当用户运行你的应用程序,在你的AppDelegate.m文件(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法,设置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"]; 
+0

感谢您的回答。我决定以这种方式加载视图,以便用户不需要等待,但也可以保持呼叫以防会话失效。 – vejmartin 2014-08-27 23:17:10

+0

只要世界那个地方的东西运行良好,我很高兴。 :) – avismara 2014-08-27 23:19:06