如何从NSURLSession与Swift获取cookie? [英] How to get cookie from a NSURLSession with Swift?
问题描述
我有一个调用dataTaskWithRequest的NSURLSession,以便以这种方式发送POST请求。
I have a NSURLSession that calls dataTaskWithRequest in order to send a POST request in this way
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
})
b $ b
响应等于:
response is equal to:
<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";
} }
我的问题是,我不知道如何获取cookie
My problem here is that I don't know how to get the cookie that is there in "Set-Cookie" with name MYCOOKIEIS.
我会在用户登录时使用这个,如果用户没有登录 - >登录(call login api )Else转到主屏幕并调用其他API。
I'll use this when user Login so If user is not logged in -> Login (call login api) Else Go to home screen and call other APIs.
有人可以帮我取出cookie吗?
Somebody can help me to get the cookie out of there?
我发现这个回答,但是它在Objective-C中,我不知道如何使用Swift
I found this answer but it is in Objective-C and I don't know how to do it with Swift
谢谢!
推荐答案
Swift演示文稿:
The Swift rendition might look something like:
let task = session.dataTaskWithRequest(request) { data, response, error in
if let httpResponse = response as? NSHTTPURLResponse, let fields = httpResponse.allHeaderFields as? [String : String] {
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(fields, forURL: response!.URL!)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response!.URL!, mainDocumentURL: nil)
for cookie in cookies {
var cookieProperties = [String: AnyObject]()
cookieProperties[NSHTTPCookieName] = cookie.name
cookieProperties[NSHTTPCookieValue] = cookie.value
cookieProperties[NSHTTPCookieDomain] = cookie.domain
cookieProperties[NSHTTPCookiePath] = cookie.path
cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)
let newCookie = NSHTTPCookie(properties: cookieProperties)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)
print("name: \(cookie.name) value: \(cookie.value)")
}
}
}
task.resume()
这篇关于如何从NSURLSession与Swift获取cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!