Using PLIST: Part 2 – Writing to Plist Files

Now that you have learned to open a property list and read the values into an object that can be used throughout your app, you may want to change and save some of those properties. In Part 2 we’re going to change some values and write them back to the file system. Let’s get started.

This can be done with a single simple function:

func writePropertyList(plistName: String) {
    
    let fileExtension = ".plist"
    let path = Bundle.main.resourcePath
    let filePath = URL(fileURLWithPath: path! + "/" + plistName + fileExtension)
    
    do {
        let data = try PropertyListSerialization.data(fromPropertyList: appSettings, format: .xml, options: 0)
        try data.write(to: filePath)
    } catch {
        fatalError(error as! String)
    }
}

Let’s talk about what’s going on in the code.

  • The function requires that a name value be passed in as a string. This will be the name of our new property list
  • The path variable is set to the set to be the top level path for the app itself.
  • We then create a fully qualified file path and cast it as a URL data type
  • Next we take the dictionary of values and using the data() method of the same PropertyListSerialization class we convert the data back to an XML format that can be written to the file system.
  • Finally, we write the data using the filePath URL as the destination.

Since both the data() method and the write() method can throw an error we wrap the entire block in a do/catch block and for the time being halt executing and print the error if something goes wrong.

Now that we have a method that write a property list we can call it from any place in our code. For example:

writePropertyList(plistName: "AnotherPropertyist")

Now, if you view the package contents of your app bundle you will see a new property list file with name specified in the call to writeProperyList().

Leave a Reply