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

ios – 如何从Swift中的NSURLResponse中检索cookie?,第1张

概述我有一个NSURLSession调用dataTaskWithRequest以发送POST请求.我修改了我发现 here的例子. var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println("Response: \(response)" 我有一个NSURLSession调用dataTaskWithRequest以发送POST请求.我修改了我发现 here的例子.

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

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

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

NSJsONSerialization.JsONObjectWithData(ResponseData,options: .MutableLeaves,error: &err)

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

解决方法
// Setup a NSMutableURLRequest to your desired URL to call along with a "POST" http Methodvar 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 Bodyvar 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 responseaRequest.addValue("application/Json",forhttpheaderFIEld: "Content-Type")aRequest.addValue("application/Json",forhttpheaderFIEld: "Accept")// Setup a session task which sends the above requestvar task = aSession.dataTaskWithRequest(aRequest,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()
总结

以上是内存溢出为你收集整理的ios – 如何从Swift中的NSURLResponse中检索cookie?全部内容,希望文章能够帮你解决ios – 如何从Swift中的NSURLResponse中检索cookie?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1009495.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存