Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve a cookie from a NSURLResponse in Swift?

I have a NSURLSession that calls dataTaskWithRequest in order to send a POST request. I modified the example I found here.

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    println("Response: \(response)")
            
    // Other stuff goes here

})

I can't quite seem to get the header from the response. I know the cookie I want is somewhere in the header, because when I print out the response in the above code it shows me the cookie I want. But how do I properly get the cookie out of there?

I tried parsing the JSON, but I couldn't figure out how to get the NSURLResponse into NSData for something like this:

NSJSONSerialization.JSONObjectWithData(ResponseData, options: .MutableLeaves, error: &err)
like image 660
Evan Conrad Avatar asked Mar 28 '15 20:03

Evan Conrad


2 Answers

// Setup a NSMutableURLRequest to your desired URL to call along with a "POST" HTTP Method

var aRequest = NSMutableURLRequest(URL: NSURL(string: "YOUR URL GOES HERE")!)
var aSession = NSURLSession.sharedSession()
aRequest.HTTPMethod = "POST"

// Pass your username and password as parameters in your HTTP Request's Body

var params = ["username" : "ENTER YOUR USERNAME" , "password" : "ENTER YOUR PASSWORD"] as Dictionary <String, String>
var err: NSError?
aRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

// The following header fields are added so as to get a JSON response

aRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
aRequest.addValue("application/json", forHTTPHeaderField: "Accept")

// Setup a session task which sends the above request

var task = aSession.dataTaskWithRequest(aRequest, completionHandler: {data, response, error -> Void in

     // Save the incoming HTTP Response

     var httpResponse: NSHTTPURLResponse = response as! NSHTTPURLResponse

     // Since the incoming cookies will be stored in one of the header fields in the HTTP Response, parse through the header fields to find the cookie field and save the data

     let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(httpResponse.allHeaderFields, forURL: response.URL!) as! [NSHTTPCookie]

     NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies as [AnyObject], forURL: response.URL!, mainDocumentURL: nil)

})

task.resume()
like image 62
Vishal Chandran Avatar answered Sep 19 '22 16:09

Vishal Chandran


Swift 3 update : Gives you a [HTTPCookie]

    if let url = urlResponse.url,
       let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {
       let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
    }
like image 36
Deep Parekh Avatar answered Sep 21 '22 16:09

Deep Parekh