一尘不染

从WKWebView获取所有cookie

swift

使用来获取Cookie
UIWebView似乎很简单NSHTTPCookieStorage.sharedHTTPCookieStorage(),它似乎WKWebView将Cookie存储在其他位置。

我做了一些研究,然后从NSHTTPURLResponse对象中获取了一些Cookie 。但是,其中不包含WKWebView

func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {

  if let httpResponse = navigationResponse.response as? NSHTTPURLResponse {
    if let headers = httpResponse.allHeaderFields as? [String: String], url = httpResponse.URL {
      let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headers, forURL: url)

      for cookie in cookies {
        logDebug(cookie.description)

        logDebug("found cookie " + cookie.name + " " + cookie.value)
      }
    }
  }
}

奇怪的是WKWebsiteDataStore,ios 9中还有一个类负责管理中的cookie
WKWebView,但是,该类不包含用于检索cookie数据的公共方法:

let storage = WKWebsiteDataStore.defaultDataStore()

storage.fetchDataRecordsOfTypes([WKWebsiteDataTypeCookies], completionHandler: { (records) -> Void in
  for record in records {
    logDebug("cookie record is " + record.debugDescription)

    for dataType in record.dataTypes {
      logDebug("data type is " + dataType.debugDescription)

      // get cookie data??
    }
  }
})

是否有解决方法来获取Cookie数据?


阅读 826

收藏
2020-07-07

共1个答案

一尘不染

最后,httpCookieStore对于WKWebsiteDataStore登陆iOS的11。

https://developer.apple.com/documentation/webkit/wkwebsitedatastore?changes=latest_minor

2020-07-07