iOS UIWebView 通过 cookie 完成自动登录
首先在- (void)webViewDidFinishLoad:(UIWebView *)webView方法中获取cookie并保存:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//保存cookie
// 将获取的cookie储存在沙盒中( 通过 [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie: cookies]来保存cookies,但是我发现,即使这样设置之后再app退出之后,该cookies还是丢失了(其实是cookies过期的问题)
NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSHTTPCookie *cookie;
for (id c in nCookies)
{
if ([c isKindOfClass:[NSHTTPCookie class]])
{
cookie=(NSHTTPCookie *)c;
if ([cookie.name isEqualToString:@"PHPSESSID"]) {
NSNumber *sessionOnly = [NSNumber numberWithBool:cookie.sessionOnly];
NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
[[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookie"];
break;
}
}
}
}
之后在loadRequest请求之前设置cookie,就会自动登录了:
- (void)createWkWebView{
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-49)];
_webView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_webView];
self.webView = _webView;
_webView.delegate = self;
//获取cookie
if ([[[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]allKeys]containsObject:@"cookie"]) {
//获取cookies:程序起来之后,uiwebview加载url之前获取保存好的cookies,并设置cookies,
NSArray *cookies =[[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"];
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
[cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
[cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
[cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
}
[_webView loadRequest:.........];
}