-
-
Save 16892434/07ec00884c33eca61b432c28a64f3a3e to your computer and use it in GitHub Desktop.
Load and Save JSON objects into a local file (written in Swift)
This file contains 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
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