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

标签 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 参数发送 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/

相关文章:

ios - 以编程方式更改 UIScrollView 引用

ios - glscissor 可以剪切多个区域吗?

ios - LiveSDK for iOS消息将释放实例

swift - 使用可选的数组和类型安全,最佳实践?

iphone - 在同一文件的 xCode 中显示/隐藏 View ?

swift + Xcode : use osascript in Mac App

iOS 8 swift : How to keep the keyboard displayed when the UIAlercontroller is presented modally?

ios - Spritekit (Swift) 是否允许使用两个不同的相机节点?

ios - 错误 : FBSDKApplicationDelegate. m No visible @interface for 'UIApplication' declares the selector 'openURL:options:completionHandler:'

javascript - PWA 中的 getUserMedia 与 iOS 11 上的 list