How to read response cookies using Alamofire

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.


If you just want to read all the cookies against the domain you are interacting with, you can get all cookies with this method.

let cookies = Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.cookiesForURL(NSURL(string: "mydomain.com")! )

It returns an optional array of NSHTTPCookie items. (Swift 2.2 and Alamofire 3.4)

Swift 4.1:

let cookies = Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.cookies(for: url)

Please be advised that the accepted answer does not work if the cookies are not posted within the header response. Apparently, some cookies are extracted in advance and stored in the shared cookie store and will not appear with the response.

You must use HTTPCookieStorage.shared.cookies instead.

Swift 3:

        Alamofire.request(url, method: HTTPMethod.post, parameters: parameters).responseData { (responseObject) -> Void in

            if let responseStatus = responseObject.response?.statusCode {
                if responseStatus != 200 {
                    // error
                } else {
                    // view all cookies
                    print(HTTPCookieStorage.shared.cookies!)
                }
            }
        }

Credit goes to Travis M.