Use case: I have two WKWebView
s, one in a main app and one in an app extension. I want them to share the same cookie store.
Apple APIs have 2 different cookie storage classes: WKHTTPCookieStore
and HTTPCookieStorage
.
Apple also has sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage
for URLSession
s (not WKWebView
s) to use across Apps/Build Targets/Extensions.
My plan is to transfer one WKWebKit
cookies to the sharedCookieStorage and then again to the other WKWebKit
cookie store.
Before I write one, does anyone have a simple wrapper class that takes in these classes, observes them, and keeps them synchronized?
Or is there otherwise a simpler way to do this seemingly very common use case?
This is what I put together. Important things to keep in mind:
WKWebView
cookies are set and fetched asynchronously, hence the number of callbacksWKHTTPCookieStore
. It's not perfect, butcookiesDidChange
methods are there for manually updating, say after page loadsWKWebView
within theaddCookieStore
callback to ensure the store is sync'd before the page is loadedaddCookieStore
callbacks to ensure the proper order(Sorry I couldn't use Combine for compatibility reasons)
Code: