How to make HTTP Post request with JSON body in Swift How to make HTTP Post request with JSON body in Swift json json

How to make HTTP Post request with JSON body in Swift


Try this,

// prepare json datalet json: [String: Any] = ["title": "ABC",                           "dict": ["1":"First", "2":"Second"]]let jsonData = try? JSONSerialization.data(withJSONObject: json)// create post requestlet url = URL(string: "http://httpbin.org/post")!var request = URLRequest(url: url)request.httpMethod = "POST"// insert json data to the requestrequest.httpBody = jsonDatalet task = URLSession.shared.dataTask(with: request) { data, response, error in    guard let data = data, error == nil else {        print(error?.localizedDescription ?? "No data")        return    }    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])    if let responseJSON = responseJSON as? [String: Any] {        print(responseJSON)    }}task.resume()

or try a convenient way Alamofire


Swift 4 and 5

HTTP POST request using URLSession API in Swift 4

func postRequest(username: String, password: String, completion: @escaping ([String: Any]?, Error?) -> Void) {    //declare parameter as a dictionary which contains string as key and value combination.    let parameters = ["name": username, "password": password]    //create the url with NSURL    let url = URL(string: "https://www.myserver.com/api/login")!    //create the session object    let session = URLSession.shared    //now create the Request object using the url object    var request = URLRequest(url: url)    request.httpMethod = "POST" //set http method as POST    do {        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body    } catch let error {        print(error.localizedDescription)        completion(nil, error)    }    //HTTP Headers    request.addValue("application/json", forHTTPHeaderField: "Content-Type")    request.addValue("application/json", forHTTPHeaderField: "Accept")    //create dataTask using the session object to send data to the server    let task = session.dataTask(with: request, completionHandler: { data, response, error in        guard error == nil else {            completion(nil, error)            return        }        guard let data = data else {            completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))            return        }        do {            //create json object from data            guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {                completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))                return            }            print(json)            completion(json, nil)        } catch let error {            print(error.localizedDescription)            completion(nil, error)        }    })    task.resume()}@objc func submitAction(_ sender: UIButton) {    //call postRequest with username and password parameters    postRequest(username: "username", password: "password") { (result, error) in    if let result = result {        print("success: \(result)")    } else if let error = error {        print("error: \(error.localizedDescription)")    }}

Using Alamofire:

let parameters = ["name": "username", "password": "password123"]Alamofire.request("https://www.myserver.com/api/login", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)


HTTP Post in Swift capturing the errors

let json = [ Activity.KEY_IDSUBJECT : activity.idSubject, Activity.KEY_RECORDMODE : "3", Activity.KEY_LOCATION_LONGITUDE : "0",Activity.KEY_LOCATION_LATITUDE : "0", Activity.KEY_CHECKIN : String(activity.dateCheckIn), Activity.KEY_CHECKOUT : String(activity.dateCheckOut) ]do {    let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)    // create post request    let url = NSURL(string: "https://...appspot.com/_ah/api/activityendpoint/v1/activity")!    let request = NSMutableURLRequest(URL: url)    request.HTTPMethod = "POST"    // insert json data to the request    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")    request.HTTPBody = jsonData    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in        if error != nil{            print("Error -> \(error)")            return        }        do {            let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]            print("Result -> \(result)")        } catch {            print("Error -> \(error)")        }    }    task.resume()    return task} catch {    print(error)}