Skip to content
Khoa Pham@onmyway133

How to save and load file in macOS

1 min read
class Saver {
    func makeUrl() -> URL? {
        let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
        return urls.first?.appendingPathComponent("myFile")
    }

    func save<T: Codable>(objects: [T]) throws {
        let encoder = JSONEncoder()
        let data = try encoder.encode(objects)

        guard let url = makeUrl() else {
            return
        }

        FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil)
    }

    func load<T: Codable>(completion: @escaping ([T]) -> Void) throws {
        do {
            guard let url = makeUrl() else {
                completion([])
                return
            }

            let data = try Data(contentsOf: url)
            let objects = try JSONDecoder().decode([T].self, from: data)
            completion(objects)
        } catch {
            completion([])
        }
    }
}

Keep reading

Type to search titles and full text.

↑ ↓ move↵ openPagefind