Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read response cookies using Alamofire

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?

like image 769
abinop Avatar asked Nov 29 '15 04:11

abinop


People also ask

What does Alamofire mean?

Alamofire is a wrapper for the popular networking library, AFNetworking. It simplifies a lot of the common tasks when dealing with HTTP requests and responses. Alamofire was developed by the engineers at SwiftKick Mobile, LLC in 2011. It was open-sourced to provide a reliable HTTP networking library to iOS developers.

What is the use of Alamofire?

Alamofire is a networking library written in Swift. You use it to make HTTP(S) requests on iOS, macOS and other Apple platforms. For example, to post data to a web-based REST API or to download an image from a webserver. Alamofire has a convenient API built on top of URLSession (“URL Loading System”).

What is the advantage of Alamofire?

Advantages of Using AlamofireUsing Alamofire will give a cleaner project. API call interactions (POST/GET/PUT/etc.) will be easier and more understable. Alamofire simplifies a number of common networking tasks that makes development faster and easier.


2 Answers

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.

like image 190
cnoon Avatar answered Oct 30 '22 21:10

cnoon


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.

like image 25
JRam13 Avatar answered Oct 30 '22 20:10

JRam13