【问题标题】:Swift 4 How do I write/read dictionaries to/from the document directory?Swift 4 如何在文档目录中写入/读取字典?
【发布时间】:2018-07-17 02:56:23
【问题描述】:

我有要保存到文档目录的字典形式的加密。我还希望能够从文档目录中检索这些字典以在应用程序中解密。如何在文档目录中写入/读取字典?

【问题讨论】:

标签: ios xcode swift4


【解决方案1】:

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)
    }

希望,它会起作用。

【讨论】:

    【解决方案2】:

    步骤包括

    1. 获取文档 URL
    2. 将日期写入文件
    3. 保存到磁盘

    使用这里的语法:

    https://stackoverflow.com/a/26557965/6342609

    【讨论】:

    • 我如何将字典类型写入文件?
    猜你喜欢
    • 2019-04-14
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多