2

免责声明

我知道有几个与此问题相关的问题,我已经查看了所有可能的问题,但他们似乎在询问有关如何同步 cookie 的问题。这与那些不同,在 cookie 被正确传输的意义上,它们被传输与它们可用时之间似乎存在延迟。WKWebView

情况

我有一个使用本机登录流程的应用程序,然后,身份验证后,将用户带到WKWebView应用程序的内容。WKWebsiteDataStore在's httpCookieStore( WKHTTPCookieStore)上设置 cookie 似乎存在问题。

我遇到的问题是,在我在 上设置 cookie 之后,在设置 cookie httpCookieStore(和调用的完成处理程序)与 cookie 实际可用时之间存在延迟WKWebView

本质上,我调用 set cookie 方法,并在其完成处理程序中load(_:)调用WKWebView. Web 视图按预期加载,但是,在 Web 视图内部进行的第一个网络调用缺少刚刚设置的 cookie。如果我在调用第一个网络调用之前添加一个 500 毫秒的延迟,load(_:)就会WKWebView有 cookie。

代码

在我的视图控制器中:


public override func viewDidLoad() {
    super.viewDidLoad()

    let config = WKWebViewConfiguration()
    config.websiteDataStore = WKWebsiteDataStore.default()
    config.processPool = self.webProcessPool // This is a WKProcessPool that is injected

    createWebView(configuration: config)

    // This method is defined in an extension below.
    webView.configuration.websiteDataStore.httpCookieStore.set(cookies: self.cookies) {
        // This completion is called and the web page is loaded as expected
        self.webView.load(URLRequest(url: self.navigationUrl))

        // The first requests made by the content loaded do not have the session cookie
        // which should have been present from the call to `set(cookies:)` however,
        // instead of calling load right away as we did above, if we add a delay here 
        // such as:
        //
        // self.cookieSettingDelaySubscribtion = Observable<Int>
        //        .interval(.milliseconds(500), scheduler: MainScheduler.instance)
        //        .take(1)
        //        .subscribe({ [unowned self] _ in
        //            self.webView.load(URLRequest(url: self.navigationUrl))
        //            self.cookieSettingDelaySubscribtion.dispose()
        //        })
        //
        // The cookie will be present on the first requests every time. 
    }
}


private func createWebView(configuration: WKWebViewConfiguration) {
    webView = WKWebView(frame: view.frame, configuration: configuration)

    // Setup code follows here 
}
extension WKHTTPCookieStore {
    /// Set multiple cookies, with a single completion handler.
    /// - parameters:
    ///   - cookies: The cookies to set.
    ///   - completion: A completion block to be called when all cookies have been set. The block
    ///                 will be called on the main queue.
    public func set(cookies: [HTTPCookie], completion: @escaping () -> Void) {
        let completionDispatchGroup = DispatchGroup()

        for cookie in cookies {
            completionDispatchGroup.enter()
            setCookie(cookie) {
                completionDispatchGroup.leave()
            }
        }

        completionDispatchGroup.notify(queue: .main, execute: completion)
    }
}

问题

我想这里的问题是任何人都可以解释为什么在设置的 cookie 和调用其完成处理程序之间存在延迟,以及当 cookie 在内部实际可用时WkWebView,有没有办法(显然在设置的 cookie 完成之外因为这已经发生了)知道什么时候 cookie 在WKWebView?

4

0 回答 0