WKWebView同步cookie操作

2020-10-18  本文已影响0人  桥下醉翁

需求说明

不完美的解决方案

随之带来的问题

表面上实现了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信息的,所以又要求着服务端修改请求规则了。

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

上一篇 下一篇

猜你喜欢

热点阅读