2

I have encryptions in the form of dictionaries that I want to save to the document directory. I also want to be able to retrieve these dictionaries from the document directory to decrypt within the app. How can I write/read dictionaries to/from the document directory?

Hochunseng
  • 69
  • 1
  • 5
  • 1
    Possible duplicate of [How to write Dictionary to a file?](https://stackoverflow.com/questions/42804845/how-to-write-dictionary-to-a-file) – nayem Jul 17 '18 at 03:56

2 Answers2

2

Dictionary has its own write method which writes a property list representation of the contents of the dictionary to a given URL. You can do it using below code:

Write

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

Read

    if let dictionary = NSMutableDictionary(contentsOf: URL){
        print(dictionary)
    }

Hope, it will work.

vikzilla
  • 3,998
  • 6
  • 36
  • 57
Shamim Hossain
  • 1,690
  • 12
  • 21
0

Steps include

  1. Get Document URL
  2. Write Date to File
  3. Saving to Disk

Make use of syntax from here:

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

Mithra Singam
  • 1,905
  • 20
  • 26