无法在swift中调用post请求中的错误

时间:2015-03-03 10:44:23

标签: ios swift

代码:

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 arguments发送postrequest。它给出了错误“无法使用类型'的参数列表调用'JSONObjectWithData'(NSString?,options:NSJSONReadingOptions,error:nil)”。为什么我收到此错误?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

var strData = NSString(data: data, encoding: NSUTF8StringEncoding)

创建一个字符串,而不是NSData,所以你只需要像这样调用JSONObjectWithData

NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary