Skip to content

Instantly share code, notes, and snippets.

@jalakoo
Created April 25, 2016 03:56
Show Gist options
  • Save jalakoo/9a3ac6889565dc5a6486936ce5720ba3 to your computer and use it in GitHub Desktop.
Save jalakoo/9a3ac6889565dc5a6486936ce5720ba3 to your computer and use it in GitHub Desktop.
Simple JSON REST Get
// Attempts to return requested data as Json in closure
class func getJSON(urlString:String, completion:(json:AnyObject?, response:NSHTTPURLResponse?, error:NSError?)->()){
let session = NSURLSession.sharedSession()
let url = NSURL(string: urlString)!
// Make the POST call and handle it in a completion handler
session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Session error
if error != nil {
completion(json: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(json:nil, response:nil, error:error)
return
}
// 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(json:nil, response:responseActual, error:error)
return
}
do {
// Parse JSON
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
completion(json:jsonDictionary, response:responseActual, error:nil)
} catch {
let error = NSError(domain: "com.jalakoo.resthandler", code:400, userInfo: [NSLocalizedDescriptionKey:"Problem parsing data \(data) as JSON.",
NSLocalizedFailureReasonErrorKey:"Data was not of type JSON.",
NSLocalizedRecoverySuggestionErrorKey:"Check expected response from \(urlString)"
])
completion(json:nil, response:responseActual, error:error)
}
}).resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment