3

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", 
"field_shouji": 
  { "und": 
    [{ 
      "value": "15652344931" 
    }] 
  }
}

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

2 Answers 2

5

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

Swift 4

Since Swift 3 and 4 Apple is starting to remove NS* stuff (even that many of them are just aliases to NS*) we'll use more Swift way

//Method just to execute request, assuming the response type is string (and not file)
func HTTPsendRequest(request: URLRequest,
                     callback: @escaping (Error?, String?) -> Void) {
    let task = URLSession.shared.dataTask(with: request) { (data, res, err) in
        if (err != nil) {
            callback(err,nil)
        } else {
            callback(nil, String(data: data!, encoding: String.Encoding.utf8))
        }
    }
    task.resume()
}

// post JSON
func HTTPPostJSON(url: String,  data: Data,
                  callback: @escaping (Error?, String?) -> Void) {
    
    var request = URLRequest(url: URL(string: url)!)
    
    request.httpMethod = "POST"
    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("application/json",forHTTPHeaderField: "Accept")
    request.httpBody = data
    HTTPsendRequest(request: request, callback: callback)
}

Usage example

var dict = Dictionary<String, Any>()

dict["username"] = "hello"
dict["password"] = "swift"
let data = try JSONSerialization.data(withJSONObject: dict, options: [])

HTTPPostJSON(url: "http://example.com/login", data: data) { (err, result) in
    if(err != nil){
        print(err!.localizedDescription)
        return
    }
    print(result ?? "")
}

Swift < 4

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)
                }
        }
        
        task.resume()
}

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

Usage example

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
    println(response);
}
Sign up to request clarification or add additional context in comments.

Comments

2

In the above answer one code line should be changed as follows

var json = NSDictionary() code should change as let json = NSMutableDictionary()

Because NSDictionary() is immutable and NSMutableDictionary() is mutable

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.