iOS UIWebView和WKWebView 设置,获取,清除cookie
1.设置cookie
NSURLRequest *request =[NSURLRequest requestWithURL:url];
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"key" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"value" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"dev.skyfox.org" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"dev.skyfox.org" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
设置失效时间
[cookieProperties setObject:[NSDate dateWithTimeIntervalSinceNow:5] forKey:NSHTTPCookieExpires];
设置sessionOnly
[cookieProperties setObject:@"0" forKey:NSHTTPCookieDiscard];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
加载网页
[webView loadRequest:request];
2.取出cookie
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];NSHTTPCookie *cookie;
for (id c in nCookies){
if ([c isKindOfClass:[NSHTTPCookie class]]){
cookie=(NSHTTPCookie *)c;
NSLog(@"%@: %@", cookie.name, cookie.value);}
}
}
3.清除cookie
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookieArray = [NSArray arrayWithArray:[cookieJar cookies]];
for (id obj in cookieArray) {
[cookieJar deleteCookie:obj];
}