1

i need to send the json request parameters to the server using nsurl session in swift2.0. i don't know how to create the json request params.i created the params like this

let jsonObj = ["Username":"Admin", "Password":"123","DeviceId":"87878"]

   // print("Params are \(jsonObj)")

    //request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonObj, options: [])

    // or if you think the conversion might actually fail (which is unlikely if you built `params` yourself)

     do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonObj, options:.PrettyPrinted)
     } catch {
        print(error)
     }

but its not ping to the method body so i am getting the failure response

1 Answer 1

2

Try the below code.

    let parameters = ["Username":"Admin", "Password":"123","DeviceId":"87878"] as Dictionary<String, String>
    let request = NSMutableURLRequest(URL: NSURL(string:YOURURL)!)

    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

    let task = session.dataTaskWithRequest(request) { data, response, error in
        guard data != nil else {
            print("no data found: \(error)")
            return
        }

        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("Response: \(json)")
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)// Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }

    task.resume()

Hope it works for you!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.