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?
Asked
Active
Viewed 3,352 times
2
-
1Possible 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 Answers
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
- Get Document URL
- Write Date to File
- Saving to Disk
Make use of syntax from here:

Mithra Singam
- 1,905
- 20
- 26