Search code examples
swiftxcodesessioncookieswkwebview

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!


Solution

  • 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.