Last active
February 19, 2022 20:11
-
-
Save adamzarn/d9843fef9ffe65518feb2476d9ea4988 to your computer and use it in GitHub Desktop.
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
extension FileManager { | |
static var documentsDirectory: URL { | |
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) | |
return paths[0] | |
} | |
enum ObjectStorageError: Error { | |
case objectDoesNotExist | |
case objectHasWrongType | |
case couldNotEncodeObject | |
var description: String { | |
switch self { | |
case .objectDoesNotExist: return "Object Does Not Exist" | |
case .objectHasWrongType: return "Object Has Wrong Type" | |
case .couldNotEncodeObject: return "Could Not Encode Object" | |
} | |
} | |
} | |
static func readJSONObject<Object: Decodable>(ofType type: Object.Type, | |
atUrl url: URL) throws -> Object { | |
do { | |
let data = try Data(contentsOf: url) | |
return try JSONDecoder().decode(type, from: data) | |
} catch { | |
throw ObjectStorageError.objectDoesNotExist | |
} | |
} | |
static func writeJSONObject<Object: Encodable>(_ object: Encodable, | |
ofType type: Object.Type, | |
atUrl url: URL) throws { | |
guard let object = object as? Object else { | |
throw ObjectStorageError.objectHasWrongType | |
} | |
do { | |
let data = try JSONEncoder().encode(object) | |
try data.write(to: url, options: [.atomicWrite, .completeFileProtection]) | |
} catch { | |
throw ObjectStorageError.couldNotEncodeObject | |
} | |
} | |
static func deleteObject(atUrl url: URL) throws { | |
do { | |
try FileManager.default.removeItem(at: url) | |
} catch { | |
throw error | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment