iOS中关于Cookie验证登录状态【markdown】
2017-09-28 本文已影响14人
Lovell_
1、第一次进入应用,登录获取Cookie,此时如果用到的是AFN去获取接口数据,Cookie已经写入了,所以无需处理,每次请求的时候,会自动将该cookie传给后台去验证
2、将Cookie缓存到本地:
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: cookiesData forKey:@"Cookie"];
[defaults synchronize];
3、当第二次进入应用的时候,先判断NSUserDefault是否有缓存的Cookie,如果有,需要将cookie写入,然后进入应用
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"Cookie"]];
NSHTTPCookieStorage * cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie * cookie in cookies){
[cookieStorage setCookie: cookie];
}
4、当用户选择退出登录,需要清除缓存中的cookie,同时要将NSUserDefault中的Cookie删除
(1)清除请求头中的Cookie:
NSHTTPCookieStorage *manager = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookieStorage = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *cookie in cookieStorage) {
[manager deleteCookie:cookie];
}
(2)清除NSUserDefault中的Cookie
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Cookie"];
[defaults synchronize];
注意:关于Cookie还有有效期,就看后台怎么定义,前端只要判断是否过了有效期,如果过了有效期,如果过了有效期,就需要用户重新登录,反之则不需要。