如何使用NSURLSession快速发布JSON数据

编程入门 行业动态 更新时间:2024-10-26 06:28:29
本文介绍了如何使用NSURLSession快速发布JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我坚持下面的代码.如何设置参数和post方法?

I am stuck with the below code. How do I set the param and in post method?

let params:[String:Any] = [ "email" : usr, "userPwd" : pwdCode] let url = NSURL(string:"inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication") let request = NSMutableURLRequest(URL: url!) request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = params<what should do for Json parameter> let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode != 200 { println("response was not 200: \(response)") return } } if error { println("error submitting request: \(error)") return } // handle the data of the successful response here } task.resume()

推荐答案

如果我正确理解了这个问题

if I understand the question correctly

var configuration = NSURLSessionConfiguration.defaultSessionConfiguration() var session = NSURLSession(configuration: configuration) var usr = "dsdd" var pwdCode = "dsds" let params:[String: AnyObject] = [ "email" : usr, "userPwd" : pwdCode ] let url = NSURL(string:"localhost:8300") let request = NSMutableURLRequest(URL: url!) request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err) let task = session.dataTaskWithRequest(request) { data, response, error in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode != 200 { println("response was not 200: \(response)") return } } if (error != nil) { println("error submitting request: \(error)") return } // handle the data of the successful response here var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary println(result) } task.resume()

我建议使用 AFNetworking .例如,请参见使用AFNetworking 2.0发布JSON数据.

I would suggest using AFNetworking. See for example, Posting JSON data using AFNetworking 2.0.

更多推荐

如何使用NSURLSession快速发布JSON数据

本文发布于:2023-10-12 00:16:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   快速   数据   NSURLSession   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!