OGeek|极客世界-中国程序员成长平台

标题: ios - WKHTTPCookieStorage 的 setCookie 在关闭和打开 Web View 后不返回 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:57
标题: ios - WKHTTPCookieStorage 的 setCookie 在关闭和打开 Web View 后不返回

我有下面的代码将 cookie 从一般 HTTPCookieStorage 复制到我的 webview 的 cookie 存储中。复制完所有 cookie 后,我加载 webview

    let webView = WKWebView(frame: containerView.bounds, configuration: WKWebViewConfiguration())
    webView.navigationDelegate = navigationDelegate
    containerView.addAndFillSubview(webView)
    guard let sharedCookies = HTTPCookieStorage.shared.cookies else {
        return
    }

    // For each cookie in the common store, set it in the WKWebView's store.
    for sharedCookie in sharedCookies {
        // Add a block to the dispatch group every time a cookie begins to be set in the WKWebView's store.
        wkSetCookieDispatchGroup.enter() 
        webView.configuration.websiteDataStore.httpCookieStore.setCookie(sharedCookie) {
           // Release a block from the dispatch group every time a cookie is successfully set in the WKWebView's store.
           wkSetCookieDispatchGroup.leave()
        }
    }

    // Wait for all the cookies to be successfully set (all blocks in the wkSetCookieDispatchGroup to be released)
    wkSetCookieDispatchGroup.notify(queue: .main) {
       // Load url in webView
    }

此代码第一次运行时,所有 cookie 都已设置,setCookie 的完成处理程序被调用并通知调度组。

但是,在关闭和打开此 Web View 的 n 次运行(通常是 3 或 4 次)之后,setCookie 的完成处理程序停止返回,通常是无限期地返回。有一些竞争条件正在发生,因为如果我设置断点并在每次 web View 打开时点击它们,这个问题就永远不会发生。发生一次后,设置断点有时会使其重新开始工作,有时什么也不做。

注意:这只发生在设备上。在模拟器上,这永远不会发生。

没有关于 setCookie 的 completionHandler 何时应该返回或不返回的文档,而且这是一个竞争条件,当你有断点时通常不会发生这种情况,这使得它非常难以调试。

有其他人经历过吗?有什么建议吗?我尝试在几个地方明确设置 WKProcessPool,但没有成功。我尝试在创建配置之前和之后创建 Web View 。我尝试了很多东西,但仍然失败



Best Answer-推荐答案


不确定这是否符合您的要求,但我遇到了同样的问题,发现我创建的每个 WKWebViewConfiguration 都使用相同的 cookie 存储,以便与不同的 WKWebView 一起使用。

由于我需要为我将使用的任何 wk webview 实例使用相同的 cookie,我最终做的是创建一个单例 WKWebViewConfiguration,它添加一次所需的 cookie,设置一个 WKProcessPool,然后返回一个副本。

我需要的每个不同的 wk webview 都会在副本上设置其自定义配置,但不必与 cookie 存储交互。

遇到同样的问题后似乎对我有用。

关于ios - WKHTTPCookieStorage 的 setCookie 在关闭和打开 Web View 后不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562649/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4