Cookies not getting sync with WKHTTPCookieStore

Hi All,

In my scenario i need to open secured .aspx page in WKWebView. I’m doing it by setting required cookies to webview configuration instance while its creation. Its working fine and i’m able to open secured web page in WKWebView. But if i tried to open the page multiple times by moving back and fro, its getting failed every 5th or 6th time. However its working fine with UIWebView all the time.

 

Below is my implementation:

I have taken a global instance of my WKWebsiteDataStores e.g. in AppDelegate

 

Solution Reference:  https://forums.developer.apple.com/message/335518#335518

 

//Inside my ViewController class

   //Calling
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.nonPersistentStore?.httpCookieStore.getAllCookies({ (cookies) in
          self.loadWebViewUsing(cookies: cookies)
    })

   //Load Request
    func loadWebViewUsing(cookies: [HTTPCookie]) {
        let webConfiguration: WKWebViewConfiguration = WKWebViewConfiguration()
        let groupDispatch = DispatchGroup()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let storage = WKWebsiteDataStore.nonPersistent()
        for cookie in cookies {
            groupDispatch.enter()
            storage.httpCookieStore.setCookie(cookie) {
                groupDispatch.leave()
            }
        }
        groupDispatch.notify(queue: DispatchQueue.main) {
            appDelegate.nonPersistentStore = storage
            webConfiguration.websiteDataStore = storage
            let newWebView = WKWebView(frame: self.view.frame, configuration: webConfiguration)
            newWebView.navigationDelegate = self
            self.view.insertSubview(newWebView, belowSubview: self.webView)
            self.webView.removeFromSuperview()
            self.webView = newWebView
            if let url = URL(string: "https://www.mysecuredpage.com") {
                self.webView.load(URLRequest(url: url))
            }
        }
    }

 

Debugging it using Safari Develop tool shows that getAllCookies returing me old cookies. Does it means my nonPersistent WKHTTPCookieStore going out of sync with the updated cookies.

 

Please suggest if i’m doing anything wrong or if this cookies sync issue with WKWebView is still a problem.

Test Environment: iOS 13.4 Simulator

regards,

Varun Mehta

Powered by WPeMatico

You may also like...

Comments are closed.