我需要一个将 cookie 存储在单独的 cookieStorage 中的 urlsession
在以下代码中 urlSession 中的 cookieStorage 与共享 cookieStorage 相同,是否可以创建单独的 cookie 存储
let config = URLSessionConfiguration.default
session = URLSession(configuration: config)
config.httpCookieAcceptPolicy = .always
session.configuration.httpCookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "adfadf")
let task = session.dataTask(with: URL(string: "https://www.google.com")!) { (data, response, error) in
print((response as? HTTPURLResponse)?.allHeaderFields ?? "")
DispatchQueue.main.async {
print(self.session.configuration.httpCookieStorage?.cookies ?? "wtf")
print(HTTPCookieStorage.shared === self.session.configuration.httpCookieStorage)
}
}
task.resume()
如果我使用初始化 cookie 存储,结果相同HTTPCookieStorage()
编辑
我尝试手动创建一个 cookie 存储并在请求完成后向其中添加 cookie
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url)
// cookies is not empty
self.cookieStore.setCookies(cookies, for: url, mainDocumentURL: nil)
print(self.cookieStore.cookies) //result is nil
最后我得到 nil 作为饼干