自从WKWebView推出后Apple官方及众多开发者都推荐使用它代替UIWebView,确实通过加载速度、占用内存方面的对比都要好上几个档次,索性就把项目中的浏览器控件换成了WKWebView,一开始进行的挺顺利的,正当我窃窃自喜时却遭到了当头一棒,正是被众多开发者诟病的WKWebView的cookie缓存问题,在这里咱不分析为何cookie带不上,也不分析如何解决问题,只介绍通过各种渠道找到的众多ioser解决方法中能解决问题的一种方法,废话不多说了直接上代码
1.取出cookie缓存到cookie容器中
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response; NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL]; for (NSHTTPCookie *cookie in cookies) { [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; } decisionHandler(WKNavigationResponsePolicyAllow); // 必须实现 加载 }
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { //取出cookie NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; //js函数 NSString *JSFuncString = @"function setCookie(name,value,expires) { var oDate=new Date(); oDate.setDate(oDate.getDate()+expires); document.cookie=name+'='+value+';expires='+oDate+';path=/' } function getCookie(name) { var arr = document.cookie.match(new RegExp('(^| )'+name+'=({FNXX==XXFN}*)(;|$)')); if(arr != null) return unescape(arr[2]); return null; } function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString(); }"; //拼凑js字符串 NSMutableString *JSCookieString = JSFuncString.mutableCopy; for (NSHTTPCookie *cookie in cookieStorage.cookies) { NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 1);", cookie.name, cookie.value]; [JSCookieString appendString:excuteJSString]; } //执行js [webView evaluateJavaScript:JSCookieString completionHandler:^(id obj, NSError * _Nullable error) { DebugLog(@"%@",error); }]; }
好了到此为止是可以解决同域名下的cookie携带问题,至于跨域目前没有涉及到,后续接着研究