Last active
July 11, 2017 21:51
-
-
Save lacyrhoades/4024278f97c5cb8f9a77cdcf7558fe61 to your computer and use it in GitHub Desktop.
Swift 3 object to JSON file layer
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
// | |
// JSONPersistence.swift | |
// Fobo | |
// | |
// Created by Lacy Rhoades on 7/11/17. | |
// Copyright © 2017 Colordeaf. All rights reserved. | |
// | |
import Foundation | |
import SwiftyJSON | |
protocol Initializeable { | |
init() | |
} | |
protocol JSONMappable { | |
static func decode(json: JSON) -> Self? | |
static func encode(_ object: Self) -> JSON | |
} | |
protocol JSONPersistable { | |
static var persistenceFileName: String { get } | |
static var persistenceURL: URL { get } | |
func didLoad() | |
func didPersist() | |
} | |
extension JSONPersistable { | |
static var persistenceURL: URL { | |
return FileManager() | |
.urls(for: .documentDirectory, in: .userDomainMask) | |
.first! | |
.appendingPathComponent( | |
self.persistenceFileName.appending(".json") | |
) | |
} | |
func didLoad() { | |
} | |
func didPersist() { | |
} | |
} | |
extension JSONPersistable where Self: JSONMappable, Self: Initializeable { | |
static func load() -> Self { | |
var result: Self | |
if let fileData = FileManager().contents(atPath: persistenceURL.path), | |
let stored = Self.decode(json: JSON(data: fileData)) { | |
result = stored | |
} else { | |
result = Self() | |
} | |
result.didLoad() | |
return result | |
} | |
static func persist(_ instance: Self) { | |
let url = Self.persistenceURL | |
let data = Self.encode(instance).rawString(.utf8)?.data(using: .utf8) | |
let _ = FileManager().createFile(atPath: url.path, contents: data, attributes: nil) | |
do { | |
try data?.write(to: url) | |
dl("JSONPersistable", "Wrote") | |
instance.didPersist() | |
} catch { | |
dl("JSONPersistable", "Error") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment