如何从 Swift 中的 NSURLResponse 中检索 cookie?
Posted
技术标签:
【中文标题】如何从 Swift 中的 NSURLResponse 中检索 cookie?【英文标题】:How do I retrieve a cookie from a NSURLResponse in Swift? 【发布时间】:2015-03-28 20:34:27 【问题描述】:我有一个 NSURLSession 调用dataTaskWithRequest
以发送 POST 请求。我修改了我找到的示例here。
var task = session.dataTaskWithRequest(request, completionHandler: data, response, error -> Void in
println("Response: \(response)")
// Other stuff goes here
)
我似乎无法从响应中获取标题。我知道我想要的 cookie 在标题中的某个位置,因为当我在上面的代码中打印出响应时,它会显示我想要的 cookie。但是我该如何正确地取出 cookie?
我尝试解析 JSON,但我不知道如何将 NSURLResponse 转换为 NSData,如下所示:
NSJSONSerialization.JSONObjectWithData(ResponseData, options: .MutableLeaves, error: &err)
【问题讨论】:
【参考方案1】:// 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()
【讨论】:
嗨 :)!如果您可以在您的代码中添加一个简短的解释,这样其他人可以更轻松地理解它,那就太好了。 @JakobRunge 您好,我在代码中添加了 cmets 以便于理解!希望能帮助到你! :)【参考方案2】:Swift 3 更新:给你一个 [HTTPCookie]
if let url = urlResponse.url,
let allHeaderFields = urlResponse.allHeaderFields as? [String : String]
let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
【讨论】:
... 并为将来的请求存储这些 cookie:HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
【参考方案3】:
尝试将您的 NSURLResponse 转换为 NSHTTPURLResponse,然后使用名为“allHeaderFields”的属性。该属性是一个字典,您应该在其中找到您的 Cookie。
【讨论】:
它似乎不想让我这样做。当我尝试let someResponse : NSHTTPURLResponse = response
时,它给了我一个错误提示“NSURLResponse 不能转换为类型 NSHTTPURLResponse。”
让 someResponse = 响应为 NSHTTPURLResponse【参考方案4】:
let cookies: [NSHTTPCookie]?
if let responseHeaders = response.allHeaderFields as? [String:String]
cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:request.URL!)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies!, forURL: response.URL!, mainDocumentURL: nil)
【讨论】:
以上是关于如何从 Swift 中的 NSURLResponse 中检索 cookie?的主要内容,如果未能解决你的问题,请参考以下文章