Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire request with cookies

I'm beginner and I can't figure out how to make a .GET request (however it requires autenthication) with Alamofire. I managed to do this with other web service (login) because it takes parameters argument:

parameters = [
 "username" : username
"password" : password 
]

Then:

Alamofire.request(.POST, loginUrl, parameters: parameters).responseJSON { (request, response, data, error) -> Void in

     //handling the response       
}

In response header I get some information:

[Transfer-Encoding: Identity, Server: nginx/1.4.1, Content-Type: application/json, P3P: policyref="http://www.somewebpage.com", CP="NON DSP COR CURa TIA", Connection: keep-alive, Date: Sun, 08 Mar 2015 13:49:20 GMT, Vary: Accept-Encoding, Cookie, Set-Cookie: sessionid=5xeff47e65f674a4cc5b2d54f344304b; Domain=.somedomain.com; Path=/, tbauth=1; Domain=.somedomain.com; Path=/, Content-Encoding: gzip]

It's of type [NSObject : AnyObject]

What should I do with that information to store it in NSURLDefaults and prepare valid request parameter (cookie)? Do I need all fields or just Set-Cookie?

I tried manually set parameter:

parameters = [
 "Cookie" : "sessionid=5xeff47e65f674a4cc5b2d54f344304b; Domain=.somedomain.com; Path=/, tbauth=1; Domain=.somedomain.com; Path=/"
]

but it does return error NSURLErrorDomain -1017 (NSURLErrorCannotParseResponse)

Thanks for all responses.

like image 240
Cahir09 Avatar asked Mar 08 '15 15:03

Cahir09


1 Answers

Ok, after 2 weeks I just found a solution:

let URL = NSURL(string: query)!
let mutableUrlRequest = NSMutableURLRequest(URL: URL)
mutableUrlRequest.HTTPMethod = "GET"

let prefs = NSUserDefaults.standardUserDefaults()
let cookie = prefs.valueForKey("COOKIE") as String

mutableUrlRequest.setValue(cookie, forHTTPHeaderField: "Cookie")

Alamofire.request(mutableUrlRequest).responseJSON { (request, response, data, error) -> Void in

     //handling the response       
}
like image 105
Cahir09 Avatar answered Nov 05 '22 02:11

Cahir09