S.Captain
S.Captain

Reputation: 167

Sync WKWebView Cookie to NSHTTPCookieStorage

WKWebView can manage its own cookie in WKHTTPCookieStorage, independent with NSHTTPCookieStorage. How can I sync cookie from WKHTTPCookieStore to NSHTTPCookieStorage.

My target is sync the cookies with WKHTTPCookieStore and NSHTTPCookieStorage.

I try to sync cookie with implement the observer method WKHTTPCookieStoreObserver.

- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore {
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> *array) {
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *nsHttpCookies = cookieStorage.cookies;

    //add new Cookie from wkWebView
    [array enumerateObjectsUsingBlock:^(NSHTTPCookie *cookie, NSUInteger idx, BOOL *stop) {
        if(![nsHttpCookies containsObject:cookie]){
            [cookieStorage setCookie:cookie];
        }
    }];

    //add old Cookie from wkWebView
    [nsHttpCookies enumerateObjectsUsingBlock:^(NSHTTPCookie *cookie, NSUInteger idx, BOOL *stop) {
        if(![array containsObject:cookie]){
            [cookieStorage deleteCookie:cookie];
        }
    }];
}];
}

It's the right way to sync the cookie from WKWebView to NSHTTPCookieStorage?

Upvotes: 3

Views: 6847

Answers (1)

Lloyd Keijzer
Lloyd Keijzer

Reputation: 1249

As Ben answered in a comment you need to extract the cookies from the response header and set them manual in the HTTPCookieStorage.

Swift 4:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void) {
    guard
        let response = navigationResponse.response as? HTTPURLResponse,
        let url = navigationResponse.response.url
    else {
        decisionHandler(.cancel)
        return
    }

    if let headerFields = response.allHeaderFields as? [String: String] {
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
        cookies.forEach { (cookie) in
             HTTPCookieStorage.shared.setCookie(cookie)
        }
    }

    decisionHandler(.allow)
}

Objective-C:

NSHTTPURLResponse * resp = (NSHTTPURLResponse*)[navigationResponse response];
NSDictionary  *diction = [resp allHeaderFields];

NSArray * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:diction forURL:[resp URL]];

for (NSHTTPCookie *cookie in cookies) {
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}

return decisionHandler(YES);

Upvotes: 3

Related Questions