Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving cookies in Alamofire (Swift)

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.

like image 888
Zac Avatar asked Jan 30 '16 18:01

Zac


1 Answers

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()

like image 169
Knuckles Huang Avatar answered Sep 28 '22 12:09

Knuckles Huang