4

We are copying cookies from WKWebView to HTTPCookitStorage.shared to be used by URLSession tasks.

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

    if let response = navigationResponse.response as? HTTPURLResponse {

        var headers = [String : String]()
        for (header, value) in response.allHeaderFields {
            headers[(header as? String)!] = value as? String
        }
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: response.url!)
        for cookie: HTTPCookie in cookies {
            print(cookie)
            HTTPCookieStorage.shared.setCookie(cookie)
        }
    }

    decisionHandler(.allow)

}

That captures most cookies, but not if there was a 302 redirect happening in the WKWebView. Is there a delegate method or some other technique that I can do to capture the cookies from a response that has a 302 response code?

Jason Hocker
  • 6,879
  • 9
  • 46
  • 79
  • Did you find a solution to this problem? I'm having the same issue – M_G Sep 26 '16 at 15:13
  • 2
    No. We used UIWebView for the login, captured the cookies. Used a WKUserScript to copy the cookies into the WKWebView. – Jason Hocker Sep 26 '16 at 18:37
  • from what I've seen there is no WKNavigationDelegate method that permits access to response headers and so on. Hoping that iOS 11 will solve some of these limitations. – Max MacLeod Sep 05 '17 at 08:09
  • ps. question does look like a possible duplicate of https://stackoverflow.com/questions/40659341/wkwebview-cant-carry-cookie-for-302-redirect and https://stackoverflow.com/questions/44576468/when-redirect-with-code-302-wkwebview-cannot-set-cookie – Max MacLeod Sep 05 '17 at 08:15
  • @MaxMacLeod Those questions are duplicates of this post – Jason Hocker Sep 05 '17 at 14:16
  • yes you're right. Unfortunately I can't close them as there's no upvoted or accepted answer. – Max MacLeod Sep 05 '17 at 14:42

1 Answers1

0

Try using PWKWebView to replace your original WKWebView.

Xingxing
  • 580
  • 1
  • 6
  • 17