How to read response cookies using Alamofire

abinop picture abinop · Nov 29, 2015 · Viewed 15.7k times · Source

I am trying to read the response cookies for a post request, as done by Postman below

enter image description here

The way I am trying without success right now is

    var cfg = NSURLSessionConfiguration.defaultSessionConfiguration()
    var cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    cfg.HTTPCookieStorage = cookies
    cfg.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always

    var mgr = Alamofire.Manager(configuration: cfg)


    mgr.request(.POST, "http://example.com/LoginLocalClient", parameters: parameters).responseJSON { response in

                print(response.response!.allHeaderFields)

                print(NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies)
}

The first print statement contains the 10 header fields without the cookies, the second one contains an empty array.

Any ideas?

Answer

cnoon picture cnoon · Dec 10, 2015

You need to extract the cookies from the response using the NSHTTPCookie cookiesWithResponseHeaderFields(_:forURL:) method. Here's a quick example:

func fetchTheCookies() {
    let parameters: [String: AnyObject] = [:]

    Alamofire.request(.POST, "http://example.com/LoginLocalClient", parameters: parameters).responseJSON { response in
        if let
            headerFields = response.response?.allHeaderFields as? [String: String],
            URL = response.request?.URL
        {
            let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
            print(cookies)
        }
    }
}

Swift 5

func fetchTheCookies() {
    let parameters: [String: AnyObject] = [:]

    Alamofire.request(.POST, "http://example.com/LoginLocalClient", parameters: parameters).responseJSON { response in
        if let headerFields = response.response?.allHeaderFields as? [String: String], let URL = response.request?.url
        {
             let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: URL)
             print(cookies)
        }
    }
}

All the configuration customization you are attempting to do won't have any affect. The values you have set are already all the defaults.