5

在 iOS 11 应用程序中,我在 WKWebView 中设置了 cookie,并通过在 safari 检查器中查看它们来验证它们是否已设置。但是,我不相信他们在我的请求中被传递。webView.configuration.websiteDataStore.httpCookieStore除了设置它们以让它们发送请求之外,我还需要做些什么吗?

我将在这里添加我的幼稚代码,任何建议都会非常有帮助:

private func setCookies(for request: URLRequest) {

    // this seems to contain the session cookies I want
    guard let storedCookies = HTTPCookieStorage.shared.cookies(for: request.url!) else { return }

    if #available(iOS 11.0, *) {

        //what cookies exist currently in the webview store
        self.webView.configuration.websiteDataStore.httpCookieStore.getAllCookies({ (webViewCookies) in

            storedCookies.forEach({ (cookie) in

                if !webViewCookies.contains(cookie) {

                    //if the webview doesn't contain the stored cookie, add it
                    self.webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie, completionHandler: {

                        if let last = storedCookies.last, last == cookie {

                            //after adding the last cookie, load the request
                            self.webView.load(request)
                        }
                    })
                }
            })
        })
    }
}
4

0 回答 0