Skip to content

Instantly share code, notes, and snippets.

@AshvinGudaliya
Created April 26, 2018 13:28
Show Gist options
  • Save AshvinGudaliya/0a5b603b0f4e179281974991ca8ee783 to your computer and use it in GitHub Desktop.
Save AshvinGudaliya/0a5b603b0f4e179281974991ca8ee783 to your computer and use it in GitHub Desktop.
Load and store a Codable Class in file
//
// AGCodableStorage.swift
// BaseProject
//
// Created by thirdeyes Infotech Pvt Ltd on 05/04/18.
// Copyright © 2018 AshvinGudaliya. All rights reserved.
//
import UIKit
class AGCodableStorage: NSObject {
fileprivate var directory: Directory = .caches
fileprivate var fileName: FileName = .tempFiles
fileprivate var fileUrl: URL {
get{
var searchPathDirectory: FileManager.SearchPathDirectory
switch directory {
case .documents:
searchPathDirectory = .documentDirectory
case .caches:
searchPathDirectory = .cachesDirectory
}
if let url = FileManager.default.urls(for: searchPathDirectory, in: .userDomainMask).first {
return url
} else {
fatalError("Could not create URL for specified directory!")
}
}
}
enum Directory {
case documents
case caches
}
enum FileName: String {
case tempFiles = "Temps.json"
}
init(for directory: Directory, fileName: FileName){
self.directory = directory
self.fileName = fileName
super.init()
}
/// Store an encodable struct to the specified directory on disk
///
/// - Parameters:
/// - object: the encodable struct to store
/// - directory: where to store the struct
/// - fileName: what to name the file where the struct data will be stored
func store<T: Encodable>(_ object: T) {
let url = fileUrl.appendingPathComponent(fileName.rawValue, isDirectory: false)
let encoder = JSONEncoder()
do {
let data = try encoder.encode(object)
if FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.removeItem(at: url)
}
FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil)
} catch {
fatalError(error.localizedDescription)
}
}
/// Retrieve and convert a struct from a file on disk
///
/// - Parameters:
/// - fileName: name of the file where struct data is stored
/// - directory: directory where struct data is stored
/// - type: struct type (i.e. Message.self)
/// - Returns: decoded struct model(s) of data
func retrieve<T: Decodable>(as type: T.Type) -> T {
let url = fileUrl.appendingPathComponent(fileName.rawValue, isDirectory: false)
if !FileManager.default.fileExists(atPath: url.path) {
fatalError("File at path \(url.path) does not exist!")
}
if let data = FileManager.default.contents(atPath: url.path) {
let decoder = JSONDecoder()
do {
let model = try decoder.decode(type, from: data)
return model
} catch {
fatalError(error.localizedDescription)
}
} else {
fatalError("No data at \(url.path)!")
}
}
/// Remove all files at specified directory
func clear(_ directory: Directory) {
do {
let contents = try FileManager.default.contentsOfDirectory(at: fileUrl, includingPropertiesForKeys: nil, options: [])
for fileUrl in contents {
try FileManager.default.removeItem(at: fileUrl)
}
} catch {
fatalError(error.localizedDescription)
}
}
/// Remove specified file from specified directory
func remove() {
let url = fileUrl.appendingPathComponent(fileName.rawValue, isDirectory: false)
if FileManager.default.fileExists(atPath: url.path) {
do {
try FileManager.default.removeItem(at: url)
} catch {
fatalError(error.localizedDescription)
}
}
}
/// Returns BOOL indicating whether file exists at specified directory with specified file name
var fileExists: Bool {
let url = fileUrl.appendingPathComponent(fileName.rawValue, isDirectory: false)
return FileManager.default.fileExists(atPath: url.path)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment