gpt4 book ai didi

swift - 如何从 HTTPURLResponse 保存 Cookie

转载 作者:行者123 更新时间:2023-11-30 12:31:20 25 4
gpt4 key购买 nike

我正在开发一个登录应用程序,成功登录响应返回 2 个 cookie 后,我想从 HTTPURLResponse 的 header 中获取这 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()

最佳答案

URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0

if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}

关于swift - 如何从 HTTPURLResponse 保存 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com