在WebView中加入cookie的方法

2019-08-22  本文已影响0人  LiuffSunny

NSHTTPCookieStorage

NSHTTPCookieStorage 实现了一个管理cookie的单例对象(只有一个实例),每个cookie都是NSHTTPCookie类的实例,最为一个规则,cookie在所有应用之间共享并在不同进程之间保持同步。Session cookie(一个isSessionOnly方法返回YES的cookie)只能在单一进程中使用。

当你访问一个网站时,NSURLRequest都会帮你主动记录下来你访问的站点设置的cookie,如果 Cookie 存在的话,会把这些信息放在 NSHTTPCookieStorage 容器中共享,当你下次再访问这个站点时,NSURLRequest会拿着上次保存下来了的cookie继续去请求。原理是透过iOS提供的NSHTTPCookieStorage元件来控制所有从这个Application发出的HTTP Request,如果在UIWebview有使用iFrame或者AJAX发出的Request同样会受到影响,让cookie可以集中管理。

request 设置cookie

- (void)setCookie {
    NSURL *cookieHost = [NSURL URLWithString:ENTRUSThtmlurl];
    NSDictionary *cookieProperties =
    [NSDictionary dictionaryWithObjectsAndKeys:[cookieHost host],NSHTTPCookieDomain,[cookieHost path],NSHTTPCookiePath,@"Version",NSHTTPCookieName,CUSTOMEVERSION,NSHTTPCookieValue,nil];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
//另一种设置cookie(可参考)
- (void)setCookie{
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"cookie_user" forKey:NSHTTPCookieName];
[cookieProperties setObject:uid forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"[xxx.xxx.com](https://link.jianshu.com/?t=http://xxx.xxx.com)" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

webView 清除cookie

//清除cookies
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
[storage deleteCookie:cookie];
}

WebView 清除缓存

[[NSURLCachesharedURLCache] removeAllCachedResponses];
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];
上一篇下一篇

猜你喜欢

热点阅读