Chapter 23. Persistent Storage

Your app can save data into files that persist on the device when your app isn’t running or the device is powered down. This chapter is about how and where files are saved and retrieved. It also talks about some of the additional ways in which files can be manipulated, such as how apps can share documents with one another and with the cloud. The chapter also explains how user preferences are maintained in UserDefaults, and describes some specialized file formats and ways of working with their data, such as XML, JSON, SQLite, Core Data, PDF, and images.

The Sandbox

The device’s file contents as a whole are not open to your app’s view. Instead, a limited region of the device’s persistent storage is dedicated to each app: this is the app’s sandbox. The idea is that every app, seeing only its own sandbox, is hindered from impinging on the files belonging to other apps, and in turn is protected from having its own files impinged on by other apps. Your sandbox, and hence your data, will be deleted if the user deletes your app; otherwise, it should reliably persist.

Standard Directories

The preferred way to refer to a file or directory is with a file URL, a URL instance. The other possible way is with a file path, or pathname, which is a string; if necessary, you can convert from a file URL to a file path by asking for the URL’s path, or from a pathname to a file URL with the URL initializer init(fileURLWithPath:). But on the whole, you should try to ...

Get Programming iOS 14 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.