【问题标题】:Set WKWebView cookie accept policy in iOS 12在 iOS 12 中设置 WKWebView cookie 接受策略
【发布时间】:2018-12-13 16:42:39
【问题描述】:

目标:将第三方cookies注入WKWebView

在 iOS 12 之前,我可以通过这个 sn-p 解决问题(请参阅 https://medium.com/@flexaddicted/how-to-set-wkwebview-cookie-accept-policy-d8a2d3b77420):

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
  guard let response = navigationResponse.response as? HTTPURLResponse,
    let url = navigationResponse.response.url else {
    decisionHandler(.cancel)
    return
  }

  if let headerFields = response.allHeaderFields as? [String: String] {
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
    cookies.forEach { cookie in
      webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
    }
  }

  decisionHandler(.allow)
}

从 iOS 12 开始,WKWebView 的响应中不再提供 cookie。

https://bugs.webkit.org/show_bug.cgi?id=188691

您知道解决此问题的任何解决方法吗?

【问题讨论】:

  • 你有没有解决过这个问题?
  • @timbru31 不,对不起

标签: ios swift wkwebview


【解决方案1】:

我想我找到了解决方案,但它有点“hacky”。​​

创建一个返回 URL 的方法:

  1. 创建DispatchSemaphore发送同步请求
  2. URLSession中执行请求
  3. DataTask结束时,检索response?.url

WKWebView 中加载内容之前,请在WKWebView 中从URLSession 设置cookie。

它就像一个魅力。

func getAuthenticatedURL(from url: URL) -> URL? {
    let session = URLSession.shared
    let semaphore = DispatchSemaphore(value:0)

    var result: URL? = nil

    session.dataTask(with: url) { _, response, _ in
        result = response?.url
        semaphore.signal()
    }.resume()

    semaphore.wait()

    return result
}

let conf = WKWebViewConfiguration()

let ctrl = WKUserContentController()

conf.userContentController = ctrl

let wkDataStore = WKWebsiteDataStore.nonPersistent()

wkDataStore.removeData(
    ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),     
    modifiedSince: .distantPast) { }

HTTPCookieStorage.shared
                .cookies?
                .forEach { wkDataStore.httpCookieStore.setCookie($0) }

conf.websiteDataStore = wkDataStore

wkWebView = WKWebView(frame: .zero, configuration: conf)

// ...

// Get URL from getAuthenticatedURL and load in wkWebView

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 2013-09-27
    • 2018-12-01
    • 2018-12-23
    • 2016-02-08
    • 2021-11-26
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多