本文介绍了如何使用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数据
发布评论