我正在开发一个登录应用程序,在成功登录响应返回 2 个 cookie 后,我想从我的 HTTPURLResponse 的标头中获取这 2 个 cookie,但我不能(httpResponse 字段不包含 cookie)我如何找到并保存它们以备我将来的请求?谢谢你帮助我
我的部分代码:
let task = URLSession.shared.dataTask(with: request ) { data, response, error in
if let httpResponse = response as? HTTPURLResponse, let fields = httpResponse.allHeaderFields as? [String : String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: (response?.url!)!)
for cookie in cookies {
//print ("hi")
var cookieProperties = [HTTPCookiePropertyKey: Any]()
cookieProperties[HTTPCookiePropertyKey.name] = cookie.name
cookieProperties[HTTPCookiePropertyKey.value] = cookie.value
cookieProperties[HTTPCookiePropertyKey.domain] = cookie.domain
cookieProperties[HTTPCookiePropertyKey.path] = cookie.path
cookieProperties[HTTPCookiePropertyKey.version] = NSNumber(value: cookie.version)
cookieProperties[HTTPCookiePropertyKey.expires] = cookie.expiresDate
let newCookie = HTTPCookie(properties: cookieProperties)
HTTPCookieStorage.shared.setCookie(newCookie!)
} }
}
task.resume()