One of the benefits of iOS development that I wasn’t entirely used to being a web developer, is the ability to store data locally. Apple allows apps to store data on the device in the form of persist data. Persist data can be read between app sessions and is only deleted when you remove the app from the device. This information is one of the many things the uninstall app prompt is referring to when it asks if you would like to delete the app and all its data. It is primarily used for small things like strings, boolean, integers, etc. and not for serious things like images (for that, you should use core data).
Reading and writing persist data is remarkably simple, but this blog post contains some tips that will prevent crashes and improve your coding structure. There are three basic elements to persist data: keys, writing, and reading.
Keys are string phrases or words that reference a specific value or set of values in persist data. Information is stored with a key reference and can be retrieved and written using that same key. These keys are incredibly important and any typo can quickly cause bugs or crashes in your app. As highlighted in my blog post in the “Preventing Code-Breaking Typos with Structures” section, it is best practice to include keys as constants in a structure. This will ensure that your keys are all only explicitly typed out in one place. It makes debugging significantly easier. Here is what your keys structure will look like when storing persist data:
NSUserDefaults (aka Persist Data) are stored using the NSUserDefaults.standardUserDefaults() initializer. Instead of calling this every time you wish to use persist data, it’s easier to simply create another structure within your Constants.swift file containing the following:
Now, instead of writing NSUserDefaults.standardUserDefaults() every time, you can simply type Constants.defaults.
To write data locally into persist data, simply use this command:
Reading data is also very simple, but there is one thing to keep in mind. If you have no written any data yet, attempting to read that nil value will result in a crash. It’s good practice to add a conditional before retrieving your persist data to prevent such conundrums from occurring. The code is shown here:
That’s pretty much all there is to it. Now you can store data between app sessions! Hope you found this helpful.