WKWebView同步cookie操作

需求说明

  • WKWebView中同步cookie
  • ajax请求中,增加cookie参数
  • 在网络访问中,响应set-cookie返回值

不完美的解决方案

  • 通过在发送请求时,将NSHTTPCookieStorage中的cookies,设置到NSURLRequest请求头中
  • 通过WKProcessPool共享NSHTTPCookieStorage下的cookie
随之带来的问题

表面上实现了cookie信息的共享,但是会出现set-cookie更新不及时的情况。通过Charles工具抓包后发现,服务端重定向请求的set-cookie都没能正确设置

寻求其他的解决方案

在iOS11中,提供了WKHTTPCookieStorage类,我们通过该类寻找解决方案。

// 在请求网页之前,设置请求头的cookie信息
[self.cookieManager cookieAppendPath:urlString withTimeout:iOSTimeoutInterval handle:^(NSURLRequest *request) {
    [self.webView loadRequest:request];
}];

- (void)cookieAppendPath:(NSString *)urlString withTimeout:(long)timeoutInterval handle:(void (^)(NSURLRequest *))completion {
    NSMutableURLRequest *request = nil;
    if (timeoutInterval > 0) {
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:timeoutInterval];
    } else {
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    }
    if (request.URL.fileURL) {
        completion(request);
    } else {
        [WKWebsiteDataStore.defaultDataStore.httpCookieStore getAllCookies:^(NSArray<NSHTTPCookie *> *allCookies) {
            NSMutableString *build = [NSMutableString string];
            for (NSHTTPCookie *cookie in allCookies) {
                if ([cookie.domain rangeOfString:@"filecookies"].location == NSNotFound && ![cookie.domain hasPrefix:@"."]) {
                    [build appendFormat:@"%@=%@;", cookie.name, cookie.value];
                }
            }
            [request addValue:build forHTTPHeaderField:@"Cookie"];
            completion(request);
        }];
    }
}

本想通过dispatch_semaphore_t做个信号量,直接同步返回request数据,结果尝试失败。问题应该在getAllCookies的返回操作问题。

后续问题思考

如果WK访问的是本地文件,那么页面ajax请求是没有cookie信息的,所以又要求着服务端修改请求规则了。

如果对您有帮助,点个在赞再走吧

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。