Skip to content

Instantly share code, notes, and snippets.

@ericcgu
Created November 17, 2014 15:43
Show Gist options
  • Save ericcgu/258bac9452a7214be544 to your computer and use it in GitHub Desktop.
Save ericcgu/258bac9452a7214be544 to your computer and use it in GitHub Desktop.
JSON
extension Dictionary {
static func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? {
if let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") {
var error: NSError?
let data: NSData? = NSData(contentsOfFile: path, options: NSDataReadingOptions(), error: &error)
if let data = data {
let dictionary: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions(), error: &error)
if let dictionary = dictionary as? Dictionary<String, AnyObject> {
return dictionary
} else {
println("File '\(filename)' is not valid JSON: \(error!)")
return nil
}
} else {
println("File: \(filename), error: \(error!)")
return nil
}
} else {
println("Could not find File: \(filename)")
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment