2

I want to make a POST request and pass some parameters. The parameters I want to pass is:

- Item : String
- Length : String
- Names : String Array
- Age : String

Today I´m doing this

var URL: NSURL = NSURL(string: "URL")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)

request.HTTPMethod = "POST"
request.HTTPBody = // parameters here?
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
               (response, data, error) in
               println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

Can anyone provide help of how to pass the above parameters in my request? I´m not quite sure how to do that.

2 Answers 2

2

The thing is that the HTTPBody expect a NSData object, so you can create Dictionary with the data you need as @dsk explain in this answer and then convert it to JSON to pass as parameters using the dataWithJSONObject function, like in the following way:

var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

var values: [String: AnyObject] = [:]
values["item"] = "value"
values["length"] = "value"
values["names"] = ["value1", "value2"]
values["age"] = "value"

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

Nevertheless I strongly recommend you use Alamofire to handle all the networking process more easily.

I hope this help you.

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

Comments

0

Add a variable for your parameters:

var params: [String: AnyObject] = [:]
params["item"] = "YOUR_STRING"
params["length"] = "YOUR_STRING"
params["names"] = ["YOUR_STRING1", "YOUR_STRING2"]
params["age"] = "YOUR_STRING"

Assuming the POST is a JSON request, add them to the HTTPBody as such:

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

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.