Skip to content

Instantly share code, notes, and snippets.

@norsez
Created May 7, 2018 04:47
Show Gist options
  • Save norsez/aa3f11c0e875526e5270e7791f3891fb to your computer and use it in GitHub Desktop.
Save norsez/aa3f11c0e875526e5270e7791f3891fb to your computer and use it in GitHub Desktop.
Load and Save JSON objects into a local file (written in Swift)
import Foundation
/**
Extension to save/load a JSON object by filename. (".json" extension is assumed and automatically added.)
*/
extension JSONSerialization {
static func loadJSON(withFilename filename: String) throws -> Any? {
let fm = FileManager.default
let urls = fm.urls(for: .documentDirectory, in: .userDomainMask)
if let url = urls.first {
var fileURL = url.appendingPathComponent(filename)
fileURL = fileURL.appendingPathExtension("json")
let data = try Data(contentsOf: fileURL)
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [.mutableContainers, .mutableLeaves])
return jsonObject
}
return nil
}
static func save(jsonObject: Any, toFilename filename: String) throws -> Bool{
let fm = FileManager.default
let urls = fm.urls(for: .documentDirectory, in: .userDomainMask)
if let url = urls.first {
var fileURL = url.appendingPathComponent(filename)
fileURL = fileURL.appendingPathExtension("json")
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: [.prettyPrinted])
try data.write(to: fileURL, options: [.atomicWrite])
return true
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment