I want to store my cookies so that when i reopen the application i can restore the ones stored in the previous instance. To initialize alamofire i use:
let manager = Alamofire.Manager.sharedInstance
And my code to load cookies is:
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: URL, mainDocumentURL: nil)
But when i reboot the phone it forgets all the cookies.
For Swift 3 and Alamofire 4.4
1.Add method to save cookies in UserDefaults
func saveCookies(response: DataResponse<Any>) {
let headerFields = response.response?.allHeaderFields as! [String: String]
let url = response.response?.url
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
var cookieArray = [[HTTPCookiePropertyKey: Any]]()
for cookie in cookies {
cookieArray.append(cookie.properties!)
}
UserDefaults.standard.set(cookieArray, forKey: "savedCookies")
UserDefaults.standard.synchronize()
}
2.Use saveCookies() in Alamofire
Alamofire.request(urlString).responseJSON { response in
saveCookies(response)
}
3.Add method to load cookies from UserDefaults
func loadCookies() {
guard let cookieArray = UserDefaults.standard.array(forKey: "savedCookies") as? [[HTTPCookiePropertyKey: Any]] else { return }
for cookieProperties in cookieArray {
if let cookie = HTTPCookie(properties: cookieProperties) {
HTTPCookieStorage.shared.setCookie(cookie)
}
}
}
4.Use loadCookies() before Alamofire.request()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With