WK Cookie问题

1、cookie获取 [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
2、cookie删除 [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookice];
3、cookie添加 [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:newcookie];
4、设置请求头 request.allHTTPHeaderFields = headerDict;

1、拉取更新cookie

- (NSURLRequest *)cookieAppendRequest{
    // 拉去更新cookie
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    NSArray *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
    //Cookies数组转换为requestHeaderFields
    NSDictionary *requestHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    //设置请求头
    request.allHTTPHeaderFields = requestHeaderFields;
    NSLog(@"%@",request.allHTTPHeaderFields);
    return request;
}

2、跨域请求丢失
在代理中拉取更新

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    [[WKCookieManager shareManager] fixNewRequestCookieWithRequest:navigationAction.request];
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (NSURLRequest *)fixNewRequestCookieWithRequest:(NSURLRequest *)originalRequest{
    NSMutableURLRequest *fixedRequest;
    if ([originalRequest isKindOfClass:[NSMutableURLRequest class]]) {
        fixedRequest = (NSMutableURLRequest *)originalRequest;
    } else {
        fixedRequest = originalRequest.mutableCopy;
    }
    //防止Cookie丢失
    NSDictionary *dict = [NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies];
    if (dict.count) {
        NSMutableDictionary *mDict = originalRequest.allHTTPHeaderFields.mutableCopy;
        [mDict setValuesForKeysWithDictionary:dict];
        fixedRequest.allHTTPHeaderFields = mDict;
    }
    return fixedRequest;
}

3、WKWebsiteDataStore
[WKWebsiteDataStore defaultDataStore].httpCookieStore;

    WKHTTPCookieStore *wKHTTPCookieStore = [WKWebsiteDataStore defaultDataStore].httpCookieStore;
    [wKHTTPCookieStore getAllCookies:^(NSArray * _Nonnull array) {
        NSLog(@"%@",array);
        NSDictionary *requestHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:array];
//        request.allHTTPHeaderFields = requestHeaderFields;
    }];

你可能感兴趣的:(WK Cookie问题)