3

I have a task must finish it today , and i need your help

i want a code for swift 2 that making json post to api i tried many many maaany codes but nothing work, also i found working code for String post but it's not helping me a lot ,

i fount this code but there is a bug in :(

  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()

so any Help please ??

bsm-2000
  • 265
  • 2
  • 13
  • Possible duplicate of [Convert Dictionary to JSON in Swift](http://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift) – Eric Aya Oct 28 '15 at 17:41

1 Answers1

3

give NSJSONSerialization.dataWithJSONObject a dictionary instead of a string

So something similar to this:

let jsonObj = ["Param1":"Value2", "Param2":"value2"]
NSJSONSerialization.dataWithJSONObject(jsonObj, options: [])
Chris Brandsma
  • 11,666
  • 5
  • 47
  • 58