WKHTTPCookieStore not retrieving set Cookie.
Asked Answered
F

1

10

I'm trying to set a cookie programmatically but it's not working. The cookie gives the impression that it's valid. I then set it on the WKWebsiteDataStore.default().httpCookieStore. In the asynchronous call back I then try to get all the cookies out of the store. However, my cookie isn't there. Where's it gone!?

    let httpCookieStore = WKWebsiteDataStore.default().httpCookieStore

    var cookieProperties = [HTTPCookiePropertyKey: Any]()
    cookieProperties[.name] = "MarkCookie"
    cookieProperties[.value] = "MarkValue"
    cookieProperties[.domain] = "localhost"
    cookieProperties[.maximumAge] = 1234
    cookieProperties[.path] = "/"

    let cookie = HTTPCookie(properties: cookieProperties)!

    httpCookieStore.setCookie(cookie) {
        // This is called fine. The cookie looks ok. 
        print("Cookie set \(cookie)")

        DispatchQueue.main.async {
            httpCookieStore.getAllCookies { cookies in
                // This is empty!!!!
                print(cookies)
            }
        }
    }
Fierro answered 28/2, 2018 at 18:44 Comment(1)
Is this still an issue with iOS 11.4? In my tests it was necessary to also specify the originURL, but my problem was somewhat different.Elul
T
1

I was testing setCookie and was receiving a vexing NetworkProcessProxy::didClose “crash” message on the console for every cookie I set (though, my app, itself, was not actually crashing). And a fetch of getAllCookies (or the async method, allCookies, in my case) was returning an empty array.

So, wondering if the problem was in getAllCookies, I decided to actually open a WKWebView so I could see if the cookies were actually being delivered (i.e., trying to determine if the problem was the cookies themselves, or some idiosyncratic API behavior). But as soon as I actually had my WKWebView load the page in question, all subsequent setCookie calls were successful, as were my calls to getAllCookies/allCookies.

I haven't tracked it down entirely, but it looks like there is some WebKit initialization that needs to happen, something resolved by loading the WKWebView, if nothing else. The challenge is that while I was previously stymied, not getting past this error, now that I have successfully loading a WKWebView, I can no longer reproduce the error. (I have tried emptying the “derived data” folder, attempting in a new project or new domain, manually deleting the stored data for that domain in Safari, etc. None of these reproduce the error.) Lol.

Torchbearer answered 10/5, 2022 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.