Teja Kumar Bethina's code changed for Swift 3:
let urlStr = "http://url_to_manage_post_requests"
let url = URL(string: urlStr)
var request: URLRequest = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.timeoutInterval = 60.0
//additional headers
request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")
let bodyStr = "string or data to add to body of request"
let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
request.httpBody = bodyData
let task = URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) -> Void in
if let httpResponse = response as? HTTPURLResponse {
print("responseCode \(httpResponse.statusCode)")
}
if error != nil {
// You can handle error response here
print("\(error)")
} else {
//Converting response to collection formate (array or dictionary)
do {
let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
JSONSerialization.ReadingOptions.mutableContainers))
//success code
} catch {
//failure code
}
}
}
task.resume()