代码:
var request = NSMutableURLRequest(URL: NSURL(string:"http://../projects/quotes/index.php/synchronization/get_daily_quotes")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
var params = ["user_id":"1","number_of_quotes":"2","category_ids":"1"]as NSDictionary
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err1: NSError?
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(strData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println("json2 :\(jsonResult)")
if((err != nil)) {
println(err!.localizedDescription)
}
else {
var success = jsonResult["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
我正在尝试使用 json 参数发送 postrequest。它给我错误“无法使用类型为 '(NSString?, options: NSJSONReadingOptions, error: nil) 的参数列表调用 'JSONObjectWithData'”。为什么我收到此错误任何帮助将不胜感激。
最佳答案
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
创建一个字符串,而不是 NSData,因此您只需像这样调用 JSONObjectWithData
:
NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
关于ios - 无法在 swift 中调用 post 请求中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28829759/