Skip to content

Instantly share code, notes, and snippets.

@LeonardoCardoso
Created May 31, 2016 13:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeonardoCardoso/bdd463ad0c0ee7793f760573fd64fdfe to your computer and use it in GitHub Desktop.
Save LeonardoCardoso/bdd463ad0c0ee7793f760573fd64fdfe to your computer and use it in GitHub Desktop.
JSON Serializer and Converter for URL and String
// JSON Serializer helper class
class Serializer {
// Retrieve JSON from Url and tries to parse it
static func jsonFromUrl(url: String, completionHandler: (NSDictionary) -> (), errorHandler: (NSError?) -> ()) {
let url = NSURL(string: url)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error != nil {
errorHandler(error)
} else {
let result = NSString(data: data!, encoding: NSUTF8StringEncoding)
completionHandler(Serializer.jsonFromString(result!))
}
}
task.resume()
}
// Convert JSON string to NSDictionary
static func jsonFromString(json: NSString) -> NSDictionary {
// convert String to NSData
let data = json.dataUsingEncoding(NSUTF8StringEncoding)
var error: NSError?
// convert NSData to 'AnyObject'
let anyObj: AnyObject?
do {
anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
} catch let error1 as NSError {
error = error1
anyObj = nil
}
if(error != nil) {
print("JSON Error \(error!.localizedDescription)")
return NSDictionary()
} else {
return anyObj as! NSDictionary
}
}
}
@LeonardoCardoso
Copy link
Author

LeonardoCardoso commented May 31, 2016

     Serializer.jsonFromUrl(
            URL,
            completionHandler: { data in
                NSLog("\(data)")
            },
            errorHandler: { error in
                NSLog("\(error)")
            }
        )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment