ios - 将 WKWebView Cookie 同步到 NSHTTPCookieStorage
<p><p><code>WKWebView</code>可以在<code>WKHTTPCookieStorage</code>中管理自己的cookie,独立于<code>NSHTTPCookieStorage</code>。如何将 cookie 从 <code>WKHTTPCookieStore</code> 同步到 <code>NSHTTPCookieStorage</code>。</p>
<p>我的目标是将 cookie 与 <code>WKHTTPCookieStore</code> 和 <code>NSHTTPCookieStorage</code> 同步。</p>
<p>我尝试通过实现观察者方法 <code>WKHTTPCookieStoreObserver</code> 来同步 cookie。 </p>
<pre><code>- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore {
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> *array) {
NSHTTPCookieStorage *cookieStorage = ;
NSArray *nsHttpCookies = cookieStorage.cookies;
//add new Cookie from wkWebView
[array enumerateObjectsUsingBlock:^(NSHTTPCookie *cookie, NSUInteger idx, BOOL *stop) {
if(!){
;
}
}];
//add old Cookie from wkWebView
[nsHttpCookies enumerateObjectsUsingBlock:^(NSHTTPCookie *cookie, NSUInteger idx, BOOL *stop) {
if(!){
;
}
}];
}];
}
</code></pre>
<p>将<code>WKWebView</code>中的cookie同步到<code>NSHTTPCookieStorage</code>是正确的方法吗?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>正如 Ben 在评论中回答的那样,您需要从响应 header 中提取 cookie 并在 <code>HTTPCookieStorage</code> 中手动设置它们。</p>
<p> swift4:</p>
<pre><code>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? {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
cookies.forEach { (cookie) in
HTTPCookieStorage.shared.setCookie(cookie)
}
}
decisionHandler(.allow)
}
</code></pre>
<p> objective-C :</p>
<pre><code>NSHTTPURLResponse * resp = (NSHTTPURLResponse*);
NSDictionary*diction = ;
NSArray * cookies = ];
for (NSHTTPCookie *cookie in cookies) {
[ setCookie:cookie];
}
return decisionHandler(YES);
</code></pre></p>
<p style="font-size: 20px;">关于ios - 将 WKWebView Cookie 同步到 NSHTTPCookieStorage,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/48181336/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/48181336/
</a>
</p>
页:
[1]