iOS WKWebView Cookie Sync

Introduction to UIWebView

UIWebView has existed since iOS2. After iOS8, Apple launched a new framework WebKit, which provides a component WKWebView that replaces UIWebView. The performance problems of various UIWebView are gone, the speed is faster, the memory usage is less, and the experience is better. Here are some other advantages:
1. Great improvement in performance, stability, and functions (loading speed, memory
2. More features that support HTML5
3. Officially announced scroll refresh rate up to 60fps and built-in gestures 4.
The same JavaScript engine
as Safari5. Split UIWebViewDelegate and UIWebView into 14 classes and 3 protocols, containing the implementation of this more detailed function.
In contrast, WKWebView is much more complicated, and some commonly used APIs are as follows:

@protocol WKNavigationDelegate <NSObject>

@optional
//请求之前,决定是否要跳转:用户点击网页上的链接,需要打开新页面时,将先调用这个方法。
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
//接收到相应数据后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
// 主机地址被重定向时调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;
// 页面加载完毕时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;
//跳转失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
// 如果需要证书验证,与使用AFN进行HTTPS证书验证是一样的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler;
//9.0才能使用,web内容处理中断时会触发
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0);

@end


Cookie synchronization

Unlike UIWebView, WKWebView ignores the default network storage, NSURLCache, NSHTTPCookieStorage, NSCredentialStorage. At present, WKWebView has its own process, and also has its own storage space for storing cookies and caches. Other network classes such as NSURLConnection cannot be accessed. At the same time, the resource request initiated by WKWebView does not go through NSURLProtocol, which makes it impossible to customize the request.

Method 1. Synchronize C/S->B/S with the same domain name

If the server-side domain name is the same in C/S and B/S, it can be synchronized when WkWebView is initialized

NSURL *url = [NSURL URLWithString:urlString];
NSMutableString *cookies = [NSMutableString string];
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// 一般都只需要同步JSESSIONID,可视不同需求自己做更改
NSString * JSESSIONID;
// 获取本地所有的Cookie
NSArray *tmp = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie * cookie in tmp) {
        if ([cookie.name isEqualToString:@"JSESSIONID"]) {
            JSESSIONID = cookie.value;
            break;
        }
    }
 if (JSESSIONID.length) {
      // 格式化Cookie
      [cookies appendFormat:@"JSESSIONID=%@;",JSESSIONID];
  }
// 注入Cookie
[requestObj setValue:cookies forHTTPHeaderField:@"Cookie"];
// 加载请求
[self.wk_webView loadRequest:requestObj];

 

Method 2. Different domain names C/S->B/S


Note: We actually reloadRequest here, under normal circumstances, we should copy the original request

NSMutableURLRequest *mutableRequest = [request mutableCopy];    //拷贝request  

Method 3 3. B/S->C/S synchronization

After WkWebView receives the Response, it takes out the Cookies brought by the Response and puts it directly into the [NSHTTPCookieStorage sharedHTTPCookieStorage] container:

- (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);
}

 

Method evaluation

In all the synchronization process, we found that NSHTTPCookieStorage is used (of course UIWebView also uses this kind of automatic synchronization). For method 1, the cookie will be lost for jumping, so two methods 2 and 3 are recommended in actual use.

 

Note: Method 2 is a simple example. When different domain names are synchronized, the Domain and Path of the cookies we obtain may be different. Otherwise, we need to replace them manually, otherwise the synchronization will also fail.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325021065&siteId=291194637