ios - Swift 4 WKWebView cookies 获取和删除同步问题

标签 ios cookies swift4 wkwebview wkwebviewconfiguration

我正在制作一个应用程序,它根据 WkWebView cookie 来决定用户登录/注销和其他事件。大多数时候,它工作正常。有时,当登录 URL 成功时,它无法获取 cookie。并且在用户注销时无法删除 cookie。甚至,当我快速登录或注销时,它会显示 session 的错误/上一个标记。

我的实现是这样的:

    func loadWebView () {

    let webConfiguration = WKWebViewConfiguration()
    webView = WKWebView(frame:  UIScreen.main.bounds, configuration: webConfiguration )
    webView.customUserAgent = APP_IDENTITY.appending("|") + Utility.deviceID().appending("|") + PSUserDefaults.getFCMToken()

    webView.navigationDelegate = self
    webView.uiDelegate = self
    webView.load(DOMAIN_URL)
  }

extension WKWebView {
func load(_ urlString: String) {
    if let url = URL(string: urlString) {
        let request = URLRequest(url: url)
        load(request)
    }
}

func cleanAllCookies() {
    HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
    print("All cookies deleted")

    WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
        records.forEach { record in
                WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
                print("Cookie ::: \(record) deleted")
        }
    }
}

func refreshCookies() {
    self.configuration.processPool = WKProcessPool()
}

func removeCookies(){
    let cookie = HTTPCookie.self
    let cookieJar = HTTPCookieStorage.shared

    for cookie in cookieJar.cookies! {
        cookieJar.deleteCookie(cookie)
        print("removeCookies")
    }
 }
  }

代表是:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
 // i am getting the cookies here most of the time. Sometimes , it failed to sync the cookies from here. 
     if #available(iOS 11.0, *) {
        print(webView.configuration.websiteDataStore.httpCookieStore.getAllCookies({ (webViewCookies) in

            let wkHttpCookieStorage = WKWebsiteDataStore.default().httpCookieStore;

            wkHttpCookieStorage.getAllCookies { (cookies) in
                // Nothing comes here sometimes !
                for cookie in cookies { 
                  }
 }

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    print("decidePolicyFor navigationAction : \(navigationAction.request.url!)")
   // Each URl navigation is happen properly on time 
   }

// I was checking the HTTPCookieStorage with a timer when it fails to get cookies in didFinish (wkwbeview ...) delegate method.  
func checkHTTPCookieStorage (){

        let cookieJar = HTTPCookieStorage.shared
        for cookie in cookieJar.cookies! {
              }
  }

I also check the print(webView.configuration.websiteDataStore.httpCookieStore.getAllCookies({ (webViewCookies) in {} values with a timer when it fails to fetch cookies. Nothing works sometimes. 

注销后,我正在以各种方式从扩展方法中手动删除 cookie:

         self.webView.cleanAllCookies()
         self.webView.removeCookies()

观察:大多数情况下,它在登录时获取 cookie,并且可以在注销时删除 cookie。有时,当我应用计时器获取 cookie 时,需要 3~10 秒才能获取 cookie。有时它完全失败了。我需要重新启动应用程序然后它会获取 cookie。这太尴尬了!

我看过一些关于 wkWebview cookie 问题的博客、报告和帖子,但没有任何帮助。

我的问题:

  1. 如何始终正确获取/删除 cookie?
  2. 我的实现有什么问题吗?

谢谢大家。

最佳答案

我在不同的 iOS 版本中发现了一些奇怪的行为。某些 iOS 版本将 cookie 保存在

WKWebsiteDataStore.default().httpCookieStore 

有些iOS版本将其保存在

HTTPCookieStorage.shared.cookies!

从 web URL 接收/设置 cookie 需要 3~10 秒。我运行一个线程来检查两个商店中的 cookie。有用!

关于ios - Swift 4 WKWebView cookies 获取和删除同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54936828/

相关文章:

ios - 无法以编程方式在 View Controller 之间切换

ios - sqlite 数据库更改后 'reloadData' 时 cell.textLabel 中的旧数据

ios - UITapGesture 不适用于堆栈 View 中的 xib 文件

c# - 手动检查用户是否更改了 cookie 值

ios - 存储在用户默认值中的 Swift 4 键值字典

swift - 跳转到 for-in 循环中的索引

ios - 如何使用swift将两个加在一起的变量转换为标签文本

iphone - 如何为 iPhone 应用程序循环播放声音?

php - 在函数内部声明一个全局变量

php - 如何为现有用户更改 session cookie 域