Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send POST parameters in Swift?

Tags:

ios

swift

Here some code:

var URL: NSURL = NSURL(string: "http://stackoverflow.com")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = ?????? 
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) 
{
    (response, data, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

What should I write in request.HTTPBody if I want send POST query "key" = "value" ?

like image 275
Max Avatar asked Jul 12 '14 15:07

Max


People also ask

Can we send parameters in POST request?

In a POST request, the parameters are sent as a body of the request, after the headers. To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

How do you make HTTP requests with URLSession in Swift?

Creating a Data Task Let's use the URLSession API to perform an HTTP request. The objective is to fetch the data for an image. Before we start, we need to define the URL of the remote image. import UIKit let url = URL(string: "https://bit.ly/2LMtByx")!

What are the HTTP request methods?

The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. These are equivalent to the CRUD operations (create, read, update, and delete). GET: GET request is used to read/retrieve data from a web server.


2 Answers

No different than in Objective-C, HTTPBody expects an NSData object:

var bodyData = "key1=value&key2=value&key3=value" request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding); 

You'll have to setup the values & keys yourself in the string.

like image 86
pixel Avatar answered Sep 22 '22 05:09

pixel


Update to Swift 4.2

This code is based on pixel's answer, and is meant as an update for Swift 4.2

let bodyData = "key1=value&key2=value&key3=value"
request.httpBody = bodyData.data(using: .utf8)
like image 36
Ibrahim Avatar answered Sep 19 '22 05:09

Ibrahim