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
?
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:
Objective-C: