Saving Data in iOS

May 31 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: Property Lists

21. Challenge: Reading Property Lists

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 20. Challenge: Saving Property Lists Next episode: 22. Comparing JSON & Property Lists

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 21. Challenge: Reading Property Lists

This course was originally recorded in April 2020. It has been reviewed and all content and materials updated as of November 2021.

Transcript: 21. Challenge: Reading Property Lists

Back to back challenges, phew! Don’t worry, as you saw in the previous video it’s really simple to migrate from using JSON to using PLists.

Similar to what you did in the previous challenge, add a new method to load your prioritized tasks from the .plist file, and load them up when you initialize the task store. Have at it!

First, I added a new method to load the data from a Plist.

private func loadPListPrioritizedTasks() {
  ...
}

Then, I copied the do-catch statement from the JSON-loading method, andsimply updated the URL to read from.

do {
  let tasksData = try Data(contentsOf: tasksPListURL)
  prioritizedTasks = try decoder.decode([PrioritizedTasks].self, from: tasksData)
} catch let error {
  print(error)
}

Next up is creating a decoder, which you can do at the top of the method.

let decoder = PropertyListDecoder()

The last thing you want to do now is use this method when initializing TaskStore.

loadPListPrioritizedTasks()

Run your app and voila, you now have loaded the same Plist data that you previously stored in your Document Directory.

One final bonus item is that, if you launch the app for the first time and there is no data file to load from your Document directory, then the console will print out a warning.

You can mitigate that by checking if the file exists prior to loading it. Do that with the following call at the top of your new method.

guard FileManager.default.fileExists(atPath: tasksPListURL.path) else {
  return
}

Here you rely on FileManager once again in order to check whether a file exists at a given path. Since you already have the URL to the file you simply pass that as the parameter and, if the file doesn’t exist, you break out of the method.

The file will get created whenever any modifications are made to your tasks. Subsequent app launches will result in your app getting past this guard statement and correctly loading the Plist data.