Last active
October 28, 2017 02:06
-
-
Save dnaismyth/94eae3fd063f81a4d9a675b3c39d8ce2 to your computer and use it in GitHub Desktop.
POST request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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