Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKHTTPCookieStore getAllCookies doesn't always call completionHandler

Tags:

ios

swift

Our application allows logging in via SSO, which we do by firing up a WKWebKit view to a particular URL that communicates to our server, and eventually redirects to a URL that we are expecting. During this process we get a cookie that we need to transfer to our SessionManager, however, when trying to get the cookies from the WKHTTPCookieStore, we don't always get the callback. Here is some code:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    let httpCookieStore = WKWebsiteDataStore.default().httpCookieStore
    httpCookieStore.getAllCookies { (cookies) in
        // This block not always called!!!
    }
}

This typically happens on initial install of the app on device, and is reproducible almost always on device, but not in the simulator.

At this point I have tried everything I can think of, but I don't know why the callback is sometimes called but not always.

like image 827
lepolt Avatar asked Jan 18 '19 00:01

lepolt


1 Answers

To see all cookies you can use this code

import UIKit

import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

var webView: WKWebView?

override func viewDidLoad() {
    super.viewDidLoad()

    let configuration = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero,configuration:configuration)
    self.view = webView
}

override func viewDidAppear(_ animated: Bool) {
    let url = URL(string: "YOUR URL")

    let request = URLRequest(url: url!)

    webView?.navigationDelegate = self
    webView?.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)

    self.webView?.load(request)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if let newValue = change?[.newKey] as? Int, let oldValue = change?[.oldKey] as? Int, newValue != oldValue {

        print("NEW",change?[.newKey])
    } else {
        print("OLD",change?[.oldKey])

    }

    webView?.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
        for cookie in cookies {
            print(cookie)
        }
    }
}
}
like image 97
canister_exister Avatar answered Sep 19 '22 10:09

canister_exister