StorageKit#
Sometimes Core Data or SQLite are overkill for your app. StorageKit saves Codable objects or raw Data to disk in the app sandbox.
Install StorageKit#
StorageKit currently only supports installation via Swift Package Manager.
- In Xcode, select
File>Add Packages.... - Enter
https://github.com/SparrowTek/StorageKit.git. - Set the dependency rule (e.g. Up to Next Major Version) and add the
StorageKitproduct.
Getting started#
import StorageKit
struct User: Codable {
let name: String
let id: Int
}
Storage.Directory supports .documents and .caches. All store functions overwrite any existing file with the same name. You can customize file protection via the optional writingOptions parameter (defaults to .completeFileProtection).
Store a Codable value#
do {
let user = User(name: "Thomas", id: 123)
try Storage.store(user, to: .documents, as: "user.json")
} catch {
// handle StorageError.createURL, StorageError.removeObject, or file write errors
}
Pass a custom JSONEncoder or writingOptions if needed:
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
try Storage.store(user,
to: .documents,
as: "user.json",
encoder: encoder,
writingOptions: .noFileProtection)
Store raw Data#
let data = Data([0x01, 0x02])
try Storage.store(data, to: .caches, as: "bytes.bin", writingOptions: .completeFileProtectionUnlessOpen)
Retrieve a Codable value#
retrieve returns an optional decoded value. Supply a JSONDecoder if you need custom settings.
let user = Storage.retrieve("user.json", from: .documents, as: User.self)
Delete a file#
try Storage.remove("user.json", from: .documents)
Check existence#
let exists = Storage.fileExists("user.json", in: .documents)
Clear a directory#
Removes every file in the chosen directory. Throws StorageError.clearDirectory(failedURLs:) if any removals fail.
try Storage.clear(.caches)