20

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?

abinop
  • 3,153
  • 5
  • 32
  • 46
  • Did you ever resolve this? Alamofire's github nor the accepted answer here resolves this issue. I'm using a 3rd party API in which they use cookies for their sessions -- but I have no idea how to grab them. – JRam13 Jan 18 '17 at 22:35
  • Please see http://stackoverflow.com/a/41881600/2446178 for the correct answer – JRam13 Jan 26 '17 at 20:45

5 Answers5

31

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.

Dhanu K
  • 11,288
  • 6
  • 24
  • 38
cnoon
  • 16,575
  • 7
  • 58
  • 66
  • 3
    sadly it doesnt work for me :( also printed empty field – Tj3n Feb 04 '16 at 03:37
  • 3
    Ever figure this out? Cookies is always empty. All my headers are there except Set-Cookie, yet Android can see the Set-Cookie header.... – datWooWoo Feb 14 '16 at 23:25
  • @cnoon i'm getting the same issue and using the above code but getting 0 elements in cookie,could you please help. – Daljeet May 19 '16 at 17:22
  • Why is this answer accepted? Like others have expressed, this does not fix the issue. Cookies are always blank. – JRam13 Jan 18 '17 at 22:33
  • Please see http://stackoverflow.com/a/41881600/2446178 for correct answer. – JRam13 Jan 26 '17 at 19:47
25

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.

Community
  • 1
  • 1
JRam13
  • 1,132
  • 1
  • 15
  • 25
5

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)
Dan Loewenherz
  • 10,879
  • 7
  • 50
  • 81
skymook
  • 3,401
  • 35
  • 39
3

the above code was correct I have used in this way -

 var allCookies: [NSHTTPCookie]?
        if let headerFields = aResponse.response?.allHeaderFields as? [String: String],
            URL = aResponse.request?.URL {
            allCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
            for cookie in allCookies! {
                print(cookie)
                let name = cookie.name
                if name == "nmSession" {
                    let value = cookie.value
                    print(value)
                }
            }

        }
Prakash Raj
  • 1,943
  • 1
  • 15
  • 13
1

@lespommes

This is the only way I have received cookies. Now I can finally see Set-Cookie in a response:

    let parameters =  ["postLogin": ["login": "mymail@gmail.com", "password": "myPassword"]]

    let url = NSURL(string: "your-website-with-cookies.com")

    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

    Alamofire.request(request)
        .responseJSON { response in

            debugPrint(response)

            if response.result.isSuccess {
                ...
                }
            }else if (response.result.isFailure){
                ...
            }
    }
Boomerange
  • 616
  • 1
  • 10
  • 18