【问题标题】:WKWebView cookie storage locationWKWebView cookie存储位置
【发布时间】:2015-03-17 15:57:00
【问题描述】:

我正在将一个应用程序从UIWebView 转换为WKWebView,并且有一个自动登录功能,它通过保存一个cookie 来处理,该cookie 包含用户已通过身份验证到NSHTTPCookieStorage 的信息。但是WKWebView 似乎没有在这个位置查看 cookie,因此每次都会提示用户登录屏幕。

是否需要激活某些东西才能让 WKWebView 正确使用 cookie?

【问题讨论】:

  • 你在其他地方找到答案了吗?
  • 截至 3 月 4 日,我仍然没有找到解决方案。

标签: ios objective-c wkwebview


【解决方案1】:

目前 WKWebView 和 UIWebView 不能正常协同工作,因为没有共享相同的 cookie 存储空间。在下面的答案中进行了深入讨论。 How can I retrieve a file using WKWebView?

希望 Apple 在即将发布的更新中解决此问题。

【讨论】:

  • 我试过了,但是没有用。由于我在其他地方读到的内容,我假设 WKWebView 不遵守 NSURLRequest 协议。这里提到stackoverflow.com/a/24982211/798456
【解决方案2】:

您可以从 NSHTTPCookieStorage 读取所有 cookie,并使用 WKHTTPCookieStore(在 iOS 11 中引入)将这些 cookie 设置为 WKWebview。更多关于 WKWebview 的信息:https://developer.apple.com/videos/play/wwdc2017/220/

如果你想支持早期版本,请参考这个答案。 Can I set the cookies to be used by a WKWebView?

 // get the cookie store (WKHTTPCookieStore) from the webview
let cookieStore =webview.configuration.websiteDataStore.httpCookieStore
//create a cookie
let cookie = HTTPCookie(properties: [ HTTPCookiePropertyKey.domain: "canineschool.org", HTTPCookiePropertyKey.path: "/",HTTPCookiePropertyKey.secure: true,HTTPCookiePropertyKey.name: "ssoToken", HTTPCookiePropertyKey.value: "******"])

// set the cookie to cookieStore
cookieStore.setCookie(cookie!){ 
     //load the request. 
}

重要提示:setCookie 是一个异步请求。完成处理程序将是 设置 cookie 后调用。 https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882007-setcookie

【讨论】:

  • 我已经在我的应用程序中实现了。我已经用代码 sn-p 更新了答案。
  • 您是否遇到过任何问题,即来自您以这种方式设置 cookie 的页面的 ajax 请求不包含您设置的 cookie?在 setCookie 完成处理程序完成后,我使用 loadHTMLString 加载页面,但 ajax 请求中仍然没有正确的 cookie。不过,使用 js 设置 document.cookie 并添加 WKUSerScript 来运行 atDocumentStart 确实对我有用。我更喜欢更新后的 API。
  • 我在这里添加了 cookie 示例。看看这个项目。github.com/BKRApps/WKWebView-JS。使用 Charles 调试 cookie 和 ajax 调用。它可能会对你有所帮助。
【解决方案3】:

将本机代码中获得的 cookie(使用 NSURLConnection/NSURlsession)共享到 UIWebview 是通过将 cookie 持久化到 NSHTTPCookieStorage 来完成的,UIwebview 将这些 cookie 用于所有网络请求。但是,该技术不适用于 WKwebview。

但是,我们可以将本机代码中的 cookie 共享到 WKWebview,如下所示:

在加载 NSURLRequest 时,我们可以在 URLRequest 中加载 cookie 作为 header,然后使用 WKwebview 加载请求。

如果您希望来自 WKWebview 的所有后续 AJAX 调用也使用此 cookie,您可能希望在加载 URLRequest 时将这些 cookie 注入 WKWebview。这在下面的答案中有详细说明。 Can I set the cookies to be used by a WKWebView?

【讨论】:

    【解决方案4】:
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.processPool = webProcessPool!
    

    WKWebViewConfiguration初始化每个WKWebView,可能会让你大吃一惊!

    let webview = WKWebView(frame:rect, configuration:webConfiguration)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      • 2015-01-27
      • 2011-04-17
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多