Skip to content

Instantly share code, notes, and snippets.

@jalakoo
Created April 25, 2016 03:57
Show Gist options
  • Save jalakoo/2e4ffbfe6d1d26740a9bd74cbd47d59d to your computer and use it in GitHub Desktop.
Save jalakoo/2e4ffbfe6d1d26740a9bd74cbd47d59d to your computer and use it in GitHub Desktop.
Simple REST POST
class func postJSON(urlString:String, params:[String: AnyObject], completion:(responseDataAsString:String?, response:NSHTTPURLResponse?, error:NSError?)->()) {
let url = NSURL(string: urlString)!
let session = NSURLSession.sharedSession()
// Create request
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
} catch {
let error = NSError(domain: "com.jalakoo.resthandler", code:404, userInfo: [NSLocalizedDescriptionKey:"Failed to convert params to a JSON payload.",
NSLocalizedFailureReasonErrorKey:"JSON conversion failure.",
NSLocalizedRecoverySuggestionErrorKey:"Make sure param payload is correct:\(params)"
])
completion(responseDataAsString:nil, response: nil, error: error)
return
}
// Make the POST
session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Session error
if error != nil {
completion(responseDataAsString:nil,response: nil, error: error)
return
}
// Response not usable
guard let responseActual = response as? NSHTTPURLResponse else {
let error = NSError(domain: "com.jalakoo.resthandler", code:404, userInfo: [NSLocalizedDescriptionKey:"Response from \(urlString) not of type NSHTTPURLReponse.",
NSLocalizedFailureReasonErrorKey:"Unexpected Error.",
NSLocalizedRecoverySuggestionErrorKey:"Consult a dev."
])
completion(responseDataAsString:nil,response: nil, error: error)
return
}
// Ok check
if responseActual.statusCode != 200 {
let error = NSError(domain: "com.jalakoo.resthandler", code:responseActual.statusCode, userInfo: [NSLocalizedDescriptionKey:"Non-200 response returned:\(String(responseActual.statusCode))",
NSLocalizedFailureReasonErrorKey:"Undesired response code returned.",
NSLocalizedRecoverySuggestionErrorKey:"Try again later or check server at:\(urlString)"
])
completion(responseDataAsString:nil,response: responseActual, error: error)
return
}
// Read the JSON
let dataString = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String
// Successful completion
completion(responseDataAsString: dataString, response: responseActual, error: nil)
}).resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment