WKWebView 可以在WKHTTPCookieStorage 中管理自己的cookie,独立于NSHTTPCookieStorage 。如何将 cookie 从 WKHTTPCookieStore 同步到 NSHTTPCookieStorage 。
我的目标是将 cookie 与 WKHTTPCookieStore 和 NSHTTPCookieStorage 同步。
我尝试通过实现观察者方法 WKHTTPCookieStoreObserver 来同步 cookie。
- (void)cookiesDidChangeInCookieStoreWKHTTPCookieStore *)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];
}
}];
}];
}
将WKWebView 中的cookie同步到NSHTTPCookieStorage 是正确的方法吗?
Best Answer-推荐答案 strong>
正如 Ben 在评论中回答的那样,您需要从响应 header 中提取 cookie 并在 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);
关于ios - 将 WKWebView Cookie 同步到 NSHTTPCookieStorage,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/48181336/
|