ios - Swift 4 如何在文档目录中写入/读取字典?
问题描述
我有要保存到文档目录的字典形式的加密。我还希望能够从文档目录中检索这些字典以在应用程序中解密。如何在文档目录中写入/读取字典?
解决方案
Dictionary 有自己的 write 方法,该方法将字典内容的属性列表表示形式写入给定的 URL。您可以使用以下代码进行操作:
写
// Get application document directory path array
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
let fileName = "users"
if let documentPath = paths.first {
let filePath = NSMutableString(string: documentPath).appendingPathComponent(fileName)
let URL = NSURL.fileURL(withPath: filePath)
let dictionary = NSMutableDictionary(capacity: 0)
dictionary.setValue("valu1", forKey: "key1")
dictionary.setValue("valu2", forKey: "key2")
let success = dictionary.write(to: URL, atomically: true)
print("write: ", success)
}
读
if let dictionary = NSMutableDictionary(contentsOf: URL){
print(dictionary)
}
希望,它会奏效。
推荐阅读
- c# - Twilio,您如何处理会议中的 maxParticipants?
- jquery - WebApi 2 [POST] 方法接收到错误的值
- javascript - 随机生成的数组中的最大数
- spring-boot - 带有 SSO 的 Spring 安全性
- java - 使用 gradle 将现有的 .wsdl 文件加载到 Web 项目中
- amazon-web-services - 无法通过 SSH 连接到 Amazon EC2 实例
- python - 无法访问numpy数组的索引
- html - 如何使列的宽度相同并在宽度和高度上填充整个空间?
- database - delphi如何输出某一列下的所有行?
- unix - 使用 SqlLoader 加载数据 不要使用自动扩展表空间