简体   繁体   中英

Swift 4 How do I write/read dictionaries to/from the document directory?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM