5

In an iOS 11 app, I've set cookies in my WKWebView and verified that they're set by viewing them in safari inspector. However, I don't believe they're being passed along in my request. Is there something else I need to do besides setting them in webView.configuration.websiteDataStore.httpCookieStore to get them to send in the request?

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

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)
                        }
                    })
                }
            })
        })
    }
}
Frankie
  • 10,568
  • 2
  • 44
  • 55

0 Answers0