小编在网上查了很多wkwebview怎么去保存cookie,怎么保证cookie不丢失的资料,可大多发现说的不怎么清楚,无法处理cookie丢失的问题。在这里贴上小编的代码,让童鞋们拿来就能用。当然这是在你第一次用wkwebview加载url的时候是有cookie的情况下的,如果不是在这种情况下的,代码就需要改动一下,但原理还是一样的。
第一步:先获取cookie并保存cookie
// 此方法是收到响应开始加载后才会调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
// 获取cookie
if (@available(iOS 12.0, *)) {//iOS11也有这种获取方式,但是我使用的时候iOS11系统可以在response里面直接获取到,只有iOS12获取不到
WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray* cookies) {
[self setCookie:cookies];
}];
}else {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
[self setCookie:cookies];
}
decisionHandler(WKNavigationResponsePolicyAllow);
}
// 保存cookie到NSHTTPCookieStorage
-(void)setCookie:(NSArray *)cookies {
if (cookies.count > 0) {
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
}
先是在wkwebview的代理方法中获取到第一次加载url的cookie,并保存到NSHTTPCookieStorage中。NSHTTPCookieStorage是一个保存cookie的单例
其中获取cookie的方式在iOS12以前和iOS12以后有所区别,代码里做了分别的处理。
第二步在以后加载url时将保存在NSHTTPCookieStorage中cookie放到请求中
// 在此处获取返回的cookie
NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
[cookieDic setObject:cookie.value forKey:cookie.name];
}
// cookie重复,先放到字典进行去重,再进行拼接
for (NSString *key in cookieDic) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
[cookieValue appendString:appendString];
}
// 对链接进行UTF-8编码,防止中文字符
NSString * encodedString = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 设置请求
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.wkwebview loadRequest:request];
});
加上这两步wkwebview的cookie问题就解决了,是不是很简单也很实用呢
网友评论