Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active November 3, 2022 21:02
Show Gist options
  • Save andresr-dev/f5b9f0897e7d9bddab3987f3adacc66b to your computer and use it in GitHub Desktop.
Save andresr-dev/f5b9f0897e7d9bddab3987f3adacc66b to your computer and use it in GitHub Desktop.
This is a FileManager extension that helps you find the documents directory of the user, decode data saved in documents and save data to documents, and bellow there's a file on how to use it.
import Foundation
extension FileManager {
static var documentsDirectory: URL {
URL.documentsDirectory
}
func decode<T: Codable>(from url: URL) throws -> T {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let decoded = try decoder.decode(T.self, from: data)
return decoded
}
func save<T:Codable>(items: T, to url: URL) {
do {
let data = try JSONEncoder().encode(items)
// .atomic means that it's going to write everything at once, this should always be used.
// We use .completeFileProteccion if we want the data to be write with encryption, so the data will be available just if the user is already authenticated.
try data.write(to: url, options: [.atomic, .completeFileProtection])
} catch {
print("Error saving data to url: \(error.localizedDescription)")
}
}
func deleteItem(at url: URL) {
do {
try FileManager.default.removeItem(at: url)
} catch {
print("[๐Ÿ˜•] Couldn't delete file from url: \(url)!")
}
}
/// Delete all files older than a specified number of days from a specified directory url
/// - Parameters:
/// - url: The URL directory
/// - olderThan: A number of days as an integer
func deleteFilesFromDirectory(_ url: URL, olderThan: Int) {
guard FileManager.default.fileExists(atPath: url.path) else { return }
do {
let fileNames = try FileManager.default.contentsOfDirectory(atPath: url.path)
for fileName in fileNames {
let path = url.appendingPathComponent(fileName).path
let attributes = try FileManager.default.attributesOfItem(atPath: path)
if
let creationDate = attributes[.creationDate] as? Date,
creationDate < Calendar.current.date(byAdding: .day, value: olderThan, to: .now) ?? .now {
try FileManager.default.removeItem(atPath: path)
}
}
} catch {
print("[๐Ÿ˜•] Error trying to delete all files older than \(olderThan) days from: \(url.path), Error: \(error.localizedDescription)")
}
}
}
import Foundation
// MARK: HOW TO USE IT
struct Card: Codable, Identifiable {
var id = UUID()
let prompt: String
let answer: String
}
class ViewModel: ObservableObject {
@Published var cards: [Card]
let savePath = FileManager.documentsDirectory.appending(path: "Cards")
init() {
do {
cards = try FileManager.default.decode(from: savePath)
} catch {
print("Error getting data from url: \(error.localizedDescription)")
cards = []
}
}
private func saveData() {
FileManager.default.save(cards, to: savePath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment