WKWebView好用加载速度快,但相比较UIWebView,同步cookie就比较头疼,想要放弃WKWebView的应该不止我一个。
设置cookie一般想到的就是从NSHTTPCookieStorage中取出,然后添加到请求头。如下:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 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];
}
NSLog(@"添加的cookie的值是%@",cookieValue);
[req addValue:cookieValue forHTTPHeaderField:@"Cookie"];
这种方式添加的cookie有时效性,且难以同步。那么怎么解决呢,这时候就需要在发送请求后,NSHTTPURLResponse中取出cookie保存到本地,然后添加到WKUserScript里
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response; NSString *cookie = [response allHeaderFields][@"Set-Cookie"];
NSString *value = [[NSUserDefaults standardUserDefaults] objectForKey:@"userCookie"];
NSString *cookie = [NSString stringWithFormat:@"document.cookie = 'ana=%@;path=/';",value];
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: cookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; [configuration.userContentController addUserScript:cookieScript];
document.cookie路径视情况自己调整。这次添加完美解决了我遇到的问题,没写过文章,就只是记录一下问题和解决过程。希望对别人有帮助,以后再改进。
网友评论