Created
May 31, 2016 13:05
-
-
Save LeonardoCardoso/bdd463ad0c0ee7793f760573fd64fdfe to your computer and use it in GitHub Desktop.
JSON Serializer and Converter for URL and String
This file contains hidden or 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
// 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 | |
} | |
} | |
} |
Author
LeonardoCardoso
commented
May 31, 2016
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment