Beaver
Beaver 是一个易于使用的 iOS 文件持久存储微型库
Beaver 允许您以优雅的方式存储文件。通过扩展 Codable 类,您可以轻松地存储和检索 JSON 文件。
安装
Carthage
将以下行添加到您的 Cartfile
github "ravitripathi/Beaver"
Cocoapods
将以下行添加到您的 Podfile
pod 'Beaver', '~> 1.1'
存储和检索数据
存储文件就像调用
Beaver.default.store(data: data, to: .documents, withFileName: "Filename") { (result) in
// Utilize the result callback if needed
}
检索文件可以通过
Beaver.default.retrieve(withFileName: "Filename", from directory: .documents) { (result) in
// Utilize the result callback if needed
}
存储结果
在存储或检索文件后,将会获得一个包含以下元数据的 StorageResult
回调:
- 一个布尔值
success
标志 errorMessage
字符串filePath
URL 对象data
:正在读取或写入的项目数据对象
由底层执行的异常处理,您只需处理回调参数。
Codable 扩展
Beaver 为 Codable 对象提供了扩展。
例如,考虑以下 Codable 类:
class User: Codable {
var name: String?
var email: String?
....
}
此类对象可以直接存储
var userModel: User
userModel.store(to: .documents, withFileName: "CurrentUser") { (result) in
if result.success {
self.statusLabel.text = "The json file was saved in \(result.filePath!)"
} else {
self.statusLabel.text = result.errorMessage
}
}
检索时
userModel.retrieve(withFileName: "CurrentUser", from: .documents) { (result) in
if result.success {
//Utilize the retrived data via result.data
} else {
print(result.errorMessage))
}
}
通过直接调用 yourCodableObject.store()
,将对象的文本保存到文档目录中的 yourCodableClass
文件中,以后可以通过直接调用 yourCodableObject.retrieve()
来检索。