简体   繁体   English

Swift 持久 cookie 存储

[英]Swift persistent cookie storage

I am looking to store a cookie in swift between multiple wkwebviews.我希望在多个 wkwebview 之间的 swift 中存储一个 cookie。 I would like to be able to log in using a wkwebview and access the same information throughout my app.我希望能够使用 wkwebview 登录并在整个应用程序中访问相同的信息。 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.我的第一个问题是如何检查是否存在 cookie,以及在登录完成后是否存在 cookie,并且 url 是一个特定值,我将如何在整个应用程序中保存和访问 cookie。 I would also like to ensure the cookie is still in place upon rebooting the app.我还想确保在重新启动应用程序后 cookie 仍然存在。 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:要在多个 webviews 之间共享所有新的 cookies,您可以使用WKProcessPool ,因此只需为您的应用程序创建单个池并将其设置为您的 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:如果您想收到有关 cookies 更改的通知,您应该在创建 webview 之前向WKWebsiteDataStore添加一个观察者:

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.默认情况下,来自 web 视图的所有 cookies 都存储在应用程序启动之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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