OStack程序员社区-中国程序员成长平台

标题: ios - 将 WKWebView Cookie 同步到 NSHTTPCookieStorage [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:53
标题: ios - 将 WKWebView Cookie 同步到 NSHTTPCookieStorage

WKWebView可以在WKHTTPCookieStorage中管理自己的cookie,独立于NSHTTPCookieStorage。如何将 cookie 从 WKHTTPCookieStore 同步到 NSHTTPCookieStorage

我的目标是将 cookie 与 WKHTTPCookieStoreNSHTTPCookieStorage 同步。

我尝试通过实现观察者方法 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-推荐答案


正如 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/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4