json - Swift 2 发布 Json

标签 json swift post

我有一个任务必须今天完成,我需要你的帮助

我想要一个 swift 2 的代码,使 json 发布到 api 我尝试了很多 maaany 代码,但没有任何效果,我也找到了 String post 的工作代码,但它对我帮助不大,

我找到了这段代码,但是在 :(

  let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    let session = NSURLSession.sharedSession()
    let jsonString : NSString = "{\"Authentication\":{\"Username\":\"\(usernameTextField.text)\",\"Password\":\"\(passwordTextField.text)\"},\"RequestType\":7}"
    request.HTTPMethod = "POST"

    //request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")


    do {
        let param = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param!, options: [])
    } catch {
        print(error)
        request.HTTPBody = nil
    }


        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            // handle error
            guard error == nil
                else
            {
                return
            }
            print("Response: \(response)")
            let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Body: \(strData)")
            let json: NSDictionary?
            do {
                json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
            } catch let dataError {
                // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                print(dataError)
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
                // return or throw?
                return
            }


            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                let success = parseJSON["success"] as? Int
                print("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: \(jsonStr)")
            }

        })

        task.resume()

所以有什么帮助吗??

最佳答案

给 NSJSONSerialization.dataWithJSONObject 一个字典而不是一个字符串

类似这样的东西:

let jsonObj = ["Param1":"Value2", "Param2":"value2"]
NSJSONSerialization.dataWithJSONObject(jsonObj, options: [])

关于json - Swift 2 发布 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397376/

相关文章:

javascript - 通过 NG click 加载 JSON 数据 (JS)

ios - 如何使用 swift 监控 ios 上的音频输入 - 例如?

iOS 缺少 grant_type

android - CountDownLatch 使应用程序停止

vb.net - VB.net使用套接字发送HTTP POST请求

json - typescript JSON字符串类

json - 无法使用Flutter在Dart中写入JSON文件

html - 将 html 标签添加到 json 字符串

ios - 选择主 Storyboard或 xib 时 Xcode 6 GM 崩溃

ios - 为什么在spritekit中按下按钮时节点的速度越来越快?