Swift 4如何在文档目录中写入/读取字典?

时间:2018-07-17 02:56:24

标签: ios xcode swift4

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

2 个答案:

答案 0 :(得分:-1)

步骤包括

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

在此处使用语法:

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

答案 1 :(得分:-1)

字典有其自己的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);
    }

希望,它将起作用。