如何从Swift中的NSURLResponse中检索cookie?

Eva*_*rad 4 cookies json ios swift

我有一个NSURLSession调用dataTaskWithRequest以发送POST请求.我修改了我在这里找到的例子.

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

    // Other stuff goes here

})
Run Code Online (Sandbox Code Playgroud)

我似乎无法从响应中获得标题.我知道我想要的cookie是在标题中的某个位置,因为当我在上面的代码中打印出响应时,它会向我显示我想要的cookie.但是如何才能正确地将饼干拿出来?

我尝试解析JSON,但我无法弄清楚如何将NSURLResponse转换为NSData,如下所示:

NSJSONSerialization.JSONObjectWithData(ResponseData, options: .MutableLeaves, error: &err)
Run Code Online (Sandbox Code Playgroud)

我一直在通过堆栈循环挖掘,寻找一种从响应中获取cookie的简单方法,但我没有找到任何东西.任何帮助,将不胜感激.

Vis*_*ran 6

// 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()
Run Code Online (Sandbox Code Playgroud)

  • @JakobRunge嗨,我在代码上添加了注释,以便于理解!希望能帮助到你!:) (2认同)

小智 6

Swift 3 更新:给你一个 [HTTPCookie]

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