如何从 Swift 中的 NSURLResponse 检索 cookie?

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

我有一个 NSURLSession 调用 dataTaskWithRequest 以发送 POST 请求。我修改了我找到的示例 here.

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

})

我似乎无法从响应中得到 header。我知道我想要的 cookie 在 header 中的某个地方,因为当我在上面的代码中打印出响应时,它显示了我想要的 cookie。但是我该如何正确地取出 cookie?

我尝试解析 JSON,但我不知道如何将 NSURLResponse 放入 NSData 中,如下所示:

NSJSONSerialization.JSONObjectWithData(ResponseData, options: .MutableLeaves, error: &err)

尝试将 NSURLResponse 转换为 NSHTTPURLResponse,然后使用名为 'allHeaderFields' 的 属性。 属性 是一个字典,您应该在其中找到您的 Cookie。

// 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()
            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 3更新:给你一个[HTTPCookie]

    if let url = urlResponse.url,
       let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {
       let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
    }