我有,为了以这种方式发送POST请求如何使用Swift从NSURLSession获取cookie?
func makeRequest(parameters: String, url:String){
var postData:NSData = parameters.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String(postData.length)
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var error:NSError?
//request.HTTPBody = NSJSONSerialization.dataWithJSONObject(postData, options: nil, error: &error)
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
println("Response:\(response)")
// Other stuff goes here
})
响应呼吁dataTaskWithRequest一个NSURLSession等于:
<NSHTTPURLResponse: 0x7fcd205d0a00> { URL: http://XXX.XXX.XXX:0000/*** } { status code: 200, headers {
"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
Connection = close;
"Content-Length" = 16;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 13 Apr 2015 00:07:29 GMT";
Expires = "Thu, 19 Nov 1981 08:52:00 GMT";
Pragma = "no-cache";
Server = "Apache/2.2.15 (CentOS)";
"Set-Cookie" = "MYCOOKIEIS=12dsada342fdshsve4lorewcwd234; path=/";
"X-Powered-By" = "PHP/5.3.14 ZendServer/5.0";
} }
我这里的问题是,我不知道该怎么获取名为MYCOOKIEIS的“Set-Cookie”中的cookie。
我将在用户登录时使用此so如果用户未登录 - >登录(call login api)否则转到主屏幕并调用其他API。
有人可以帮我把cookie从那里拿出来吗?
,我发现这个answer,但它是在Objective-C,我不知道如何与斯威夫特
做谢谢!
感谢@Rob它运行完美! –
当您执行某种“注销”时,不要忘记删除cookie。请在 –
以下检查@Mellian响应请记住,某些cookie不会显示在httpResponse.allHeaderFields下。您将不得不使用iOS提供的共享cookie存储。 –