Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write Dictionary to File in Swift

I’m trying to write a simple Dictionary to a .plist file in swift. I have written the code in an extension of the Dictionary class, for convenience. Here’s what it looks like.

extension Dictionary {
    func writeToPath (path: String) {
        do {
            // archive data
            let data = try NSKeyedArchiver.archivedData(withRootObject: self,
                                                    requiringSecureCoding: true)
            // write data
            do {
                let url = URL(string: path)
                try data.write(to: url!)
            }
            catch {
                print("Failed to write dictionary data to disk.")
            }
        }
        catch {
            print("Failed to archive dictionary.")
        }
    }
}

Every time I run this I see "Failed to write dictionary data to disk." The path is valid. I’m using "/var/mobile/Containers/Data/Application/(Numbers and Letters)/Documents/favDict.plist".

The dictionary is type Dictionary<Int, Int>, and contains only [0:0] (for simplicity/troubleshooting purposes).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why doesn’t this work? Do you have a better solution for writing the dictionary to disk?

>Solution :

URL(string is the wrong API. In the file system you must use

let url = URL(fileURLWithPath: path)

as WithPath implies.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading