user3752276 user3752276 - 2 months ago 18x
Swift Question

post json request in swift

I know how to post simple json:

// Compose a query string
let postString = “firstName=James&lastName=Bond”;
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

Now the server side require the json format like:

"name": "testuser123",
"pass": "testuser123",
{ "und":
"value": "15652344931"

and the content type should be: application/json. I have googled the whole day, still could find the right way.


You need to send a valid format of JSON.
“firstName=James&lastName=Bond”; is not JSON format.

first let's write the post methods:

func HTTPsendRequest(request: NSMutableURLRequest,
    callback: (String, String?) -> Void) {
        let task = NSURLSession.sharedSession()
            .dataTaskWithRequest(request) {
                (data, response, error) -> Void in
                if (error != nil) {
                    callback("", error.localizedDescription)
                } else {
                    callback(NSString(data: data,
                        encoding: NSUTF8StringEncoding)! as String, nil)


func HTTPPostJSON(url: String,  data: NSData,
    callback: (String, String?) -> Void) {

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

        request.HTTPMethod = "POST"
        request.addValue("application/json",forHTTPHeaderField: "Content-Type")
        request.addValue("application/json",forHTTPHeaderField: "Accept")
        request.HTTPBody = data
        HTTPsendRequest(request, callback: callback)

use: we'll set NSMutableDictionary and convert it to JSON

var json = NSMutableDictionary()
json.setValue("testuser123", forKey: "name"); //set all your values..

let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(0), error: nil);
HTTPPostJSON("http;..", data:data!) { (response, error) -> Void in