Swift 2.0, Alamofire: Set cookies in HTTP Post Request

dashbashrumble picture dashbashrumble · Oct 12, 2015 · Viewed 9.7k times · Source

I want to set cookies in my HTTP POST request.

Something like the cookie field in the HTTP Request below,

version: 0.1.7
Cookie: client=Android; version=0.1.7; sellerId=SEL5483318784; key=178a0506-0639-4659-9495-67e5dffa42de
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 1431

How can I achieve this with Alamofire?

My current Alamofire request is like this,

Alamofire.request(.POST, ServerConfig.ADD_PRODUCT_URL, parameters: productJSON, encoding: .JSON, headers: nil)
     .responseJSON(completionHandler: { responseRequest, responseResponse, responseResult in
         print(responseRequest!.URL)
         print(responseResponse)
         print(responseResult)
     })

Answer

Jérémy Magrin picture Jérémy Magrin · Oct 19, 2015

I had the same problem on a project and I do something like this to solve it:

let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(response.allHeaderFields as! [String: String], forURL: response.URL!)
Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)

You just have to do this one time, because the Alamofire instance is a singleton, so for all the next request the cookie is set.

Hope it's what you are looking for :)