How to send cookies to WKWebView httpcookiestore along with request

In iOS 11, I set cookies on my WKWebView and made sure they were set by viewing them in the safari inspector. However, I do not think that they are transmitted at my request. Is there anything else I need to do besides setting them in webView.configuration.websiteDataStore.httpCookieStoreto get them to send a request?

I will add my naive code here, any suggestions will be very useful:

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
source share

Source: https://habr.com/ru/post/1691138/


All Articles