swift - 使用 URLSessionDataTask 时 Cookie 不存在

标签 swift cookies nsurlsession nsurlrequest nsurlsessiondatatask

我正在尝试使用 URLSessionDataTask 访问我的后端 API。其中一部分包括访问使用 Safari 存储的 cookie。

例如http://api.example.com/v1/getCookies后台的php代码是

echo $_COOKIE["myCookieName"];

iOS Safari 上确实存在 cookie,但是当向网站发出 URLSessionDataTask 请求时

let url: URL = URL(string: "http://api.example.com/v1/getCookies")!

let task = Foundation.URLSession(
    configuration: URLSessionConfiguration.default,
    delegate: self,
    delegateQueue: OperationQueue.main
).dataTask(with: url)

task.resume()

响应是未设置 cookie,而不是将 cookie 的值作为对请求的响应发送。似乎来自 URLSessions 的 cookie 与 Safari 中的 cookie 是分开的。

cookie 存储在域 .example.com 和路径 / 下。

有什么方法可以让我从我的应用访问在 Safari 上设置的 cookie?例如,我想要这样的东西工作(我正在做一些更复杂的事情,但这基本上显示了我想要工作的东西)

  1. 用户访问 example.com 并选择昵称
  2. 用户选择的昵称存储在 cookie 中
  3. 用户决定下载 example.com 移动应用
  4. 应用程序向 example.com 发出请求,并返回存储在 cookie 中的昵称

有没有办法做这样的事情? HTTPCookie.cookiesHTTPCookieStorage.shared.cookies 似乎都不起作用。

最佳答案

Cookie 不能在不同的应用程序之间共享,但如果您在应用程序中使用网络浏览器,则可以实现。

如果您想从 Web View 或 SFSafariViewController 拦截 cookie,以便通过 URLSession 将它们用于其他请求,您应该实现自定义 URL 协议(protocol)。详情请见 https://www.raywenderlich.com/59982/nsurlprotocol-tutorial 因此,您的应用程序内的任何请求/响应都可以被拦截(即使是来自 Web View 或任何 URL session ),并且 cookie 和其他 header 将对您可用。例如,您可以从 Web View 开始身份验证,从响应中拦截 cookie,并将它们用于您应用中的其他请求。

关于swift - 使用 URLSessionDataTask 时 Cookie 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43553453/

相关文章:

iOS 8 Swift 1.2 和 Parse - 尝试在 View 不在窗口层次结构中的 ViewController 上呈现 UIAlertController

swift - 将我的项目与 firebase 连接以发送推送通知时出错

cookies - Electron 获取 httponly cookies

swift - 如何通过 Swift URLSession 使用 cURL 请求

ios - 如何在快速按下取消按钮时取消下载请求

ios - 为什么Xcode总是不显示参数默认值的提示?

node.js - 在 Express/Connect 中解析签名 cookie 的便捷方法?

ios - 如何在 SWIFT 3 或 4 中的 REST API 调用期间安全地处理 cookie?

ios - 由 base64encodeString 组成的 NSMutableRequest 正文在作为字符串发送时被截断

swift - 第一次从 firebase 检索图像后在本地保存图像(swift 4.2 )