简体   繁体   中英

Swift persistent cookie storage

I am looking to store a cookie in swift between multiple wkwebviews. I would like to be able to log in using a wkwebview and access the same information throughout my app. My first question is how I would check if there is a cookie and if there is one after log in has been completed and the url is a specific value how I would save and access the cookie throughout the app. I would also like to ensure the cookie is still in place upon rebooting the app. Thanks for any responses in advance!

To share all new cookies between multiple webviews you can use WKProcessPool so just create the single pool for your app and set it to your webviews:

let ProcessPool = WKProcessPool()
...
let configuration = WKWebViewConfiguration()
configuration.processPool = ProcessPool
webView = WKWebView(frame: self.view.bounds, configuration: configuration)

If you want to be notified about changes with cookies you should add an observer to WKWebsiteDataStore before creating your webviews:

WKWebsiteDataStore.default().httpCookieStore.add(self)

...

extension AppDelegate : WKHTTPCookieStoreObserver {
    func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
        cookieStore.getAllCookies { cookies in
            print(cookies)
        }
    }
}

By default all cookies from webviews are stored between your app's launches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM