Recently, using WKWebView to obtain cookie s by proxy method has been unsuccessful. Later, I found that there was a problem with the newly upgraded IOS 12, so I directly added the code
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { if (@available(iOS 12.0, *)) {//IOS 11 also has this access method, but when I use IOS 11 system, I can directly access it in response, only IOS 12 can not access it 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); } -(void)setCookie:(NSArray *)cookies { if (cookies.count > 0) { for (NSHTTPCookie *cookie in cookies) { [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; } } }
Swift 4:
if #available(iOS 11, *) { webView.configuration.websiteDataStore.httpCookieStore.getAllCookies({ (cookies) in for cookie in cookies { //TODO... } }) }
In this way, the cookie can be obtained. When I use AFNetworking, the cookie is not set in the request header, but can still be received in the background. It should be shared by WKWebView and AFNetworking.
When using WKWebView for js interaction, the third party, WKWebView JavaScript bridge, is used to help us deal with native and js interaction. But after using the WKWebView JavaScript bridge, I found that the native agent method can't be used. Later, I found that as long as I set the WKWebView JavaScript bridge after the native agent and write [self.webViewBridge setWebViewDelegate:self]; the native agent method can be used normally.
self.KWWebView.navigationDelegate = self; self.KWWebView.UIDelegate = self; self.webViewBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.KWWebView]; [self.webViewBridge setWebViewDelegate:self];
I hope it can be helpful to the small partners in need. If there is something wrong, please point out the correction.