I need a urlsession that stores cookies in a separate cookieStorage
In the folllowing code the cookieStorage in urlSession is the same as the shares cookieStorage, is it possible to create a separate cookie store
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()
Same result if I initialize the cookie store using HTTPCookieStorage()
EDIT
I tried creating a cookie store manually and add cookies to it after the request is completed
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
and at the end I end up with nil as cookies
Apparently
HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "groupName")
seems to work only on iOS 10+, on iOS 9 it will return nil even if the documentation says@available(iOS 9.0, *) open class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage
You can use this workaround :