Skip to content

Instantly share code, notes, and snippets.

@dnaismyth
Last active October 28, 2017 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnaismyth/94eae3fd063f81a4d9a675b3c39d8ce2 to your computer and use it in GitHub Desktop.
Save dnaismyth/94eae3fd063f81a4d9a675b3c39d8ce2 to your computer and use it in GitHub Desktop.
POST request
typealias PostCompletionHandler = (NSDictionary) -> ()
static func post(postUrl: String, body: [String: AnyObject], completionHandler: @escaping (PostCompletionHandler)){
let url = URL(string:postUrl)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type") // Set as JSON content-type
request.addValue("application/json", forHTTPHeaderField: "Accept")
if(body.count > 0){
do {
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
}
let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
if error != nil{
print(error?.localizedDescription ?? "Error")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if json != nil {
completionHandler(json!)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment