Saving Data in iOS Part 2

Leela Prasad
Swift India
Published in
6 min readJan 22, 2019

→ File Manager :

Having more than one possibilities to store the data in iOS, we are going to learn about the FileManager today. If we want to store the data, that is app related, which we do not want to expose to other apps on the device, we need to store that kind files without exposing. That means, we do not let the files go out of our app’s sand box. So File Manager is perfectly suits for this requirement, as we can store into the user’s document directory.

A file system handles the persistent storage of data files, apps, and the files associated with the operating system itself. Therefore, the file system is one of the fundamental resources used by all processes.(from Apple Documentation).

  • About the iOS File System

Users of iOS devices do not have direct access to the file system and apps are expected to follow this convention.

→ iOS Standard Directories: Where Files Reside

For security purposes, an iOS app’s interactions with the file system are limited to the directories inside the app’s sandbox directory. A sandbox is a virtual fence around your app. It is that unique corner of device memory that iOS specifically grants access to your app. During installation of a new app, the installer creates a number of container directories for the app inside the sandbox directory. Each container directory has a specific role. The bundle container directory holds the app’s bundle, whereas the data container directory holds data for both the app and the user. The data container directory is further divided into a number of subdirectories that the app can use to sort and organise its data. The app may also request access to additional container directories — for example, the iCloud container — at runtime.

You can read from the following table(from Apple documents) to know the directories which exist and their purpose on iOS devices.

An iOS app may create additional directories in the Documents, Library, and tmp directories. You might do this to better organise the files in those locations.

→ Specifying path to a file :

The preferred way to specify the location of a file is to use the URL object. We can also use the String, but URL offer more robust way to locate files and directories.

  • For most URLs, we build the URL by concatenating directory and file names together using the appropriate URL methods until we have the path to the item. A URL built in this way is referred to as a path-based URL.
  • We also use string-based paths by concatenating directory and file-names together, with the results stored in a slightly different format than that used by the URL class.
  • We can also create a file reference URL, which identifies the location of the file or directory using a unique ID. Although these are safe to use while your app is running, file reference URLs are not safe to store and reuse between launches of app because a file’s ID may change if the system is rebooted. To store a location of a file persistently between launches of the app, we need to use bookmarks.

Examples :

Path-based URL: file://localhost/Users/steve/Documents/MyFile.txt

File reference URL: file:///.file/id=6571367.2773272/

String-based path: /Users/steve/Documents/MyFile.txt

We create URL objects using the URL methods and convert them to file reference URLs only when needed them. Path-based URLs are easier to manipulate, easier to debug, and are generally preferred by classes such as FileManager. An advantage of file reference URLs is that they are less fragile than path-based URLs while our app is running. If we move a file in the Finder, any path-based URLs that refer to the file immediately become invalid and must be updated to the new path. However, as long as the file moved to another location on the same disk, its unique ID does not change and any file reference URLs remain valid.

Of course, there are still times when we might need to use strings to refer to a file. Fortunately, the URL class provides methods to convert path-based URLs to and from String objects. We can use a string-based path when presenting that path to the user or when calling a system routine that accepts strings instead of URLs. The conversion between URL objects and String objects is done using the URL class’s method absoluteString(url.absoluteString).

Because URL and String describe only the location of a file or directory, you can create them before the actual file or directory exists.

Locating Items in the File System

Before we can access a file or directory, we need to know its location. There are several ways to locate files and directories:

  • Ask the user to specify a location.
  • Locating files in the standard system directories, in both sandboxed and non-sandboxed apps.
  • Using bookmarks.

Locating Items in the App Bundle

We use Bundle object to locate required resources which are present inside our app bundle. Bundles eliminate the need for the app to remember the location of individual files by organising those files in a specific way. The methods of the NSBundle class understand that organisation and use it to locate the app’s resources on demand. The advantage of this technique is that we can generally rearrange the contents of the bundle without rewriting the code we use to access it. Bundles also take advantage of the current user’s language settings to locate an appropriately localised version of a resource file.

Example:

var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")

Locating Items in the Standard Directories

When we need to locate a file in one of the standard directories, we use the system frameworks to locate the directory first and then use the resulting URL to build a path to the file.

Example:

The first parameter takes one of the values specified by FileManager.SearchPathDirectory. These determine what kind of standard directory you’re looking for, like “Documents” or “Caches”.

The second parameter passes a FileManager.SearchPathDomainMask value, which determines the scope of where you’re looking for. For example, .applicationDirectory might refer to /Applications in the local domain and ~/Applications in the user domain.

→ Source from (NSHipster)

Locating Files Using Bookmarks

To save the location of a file persistently, use the bookmark capabilities of URL. A bookmark is an opaque data structure, enclosed in a Data object, that describes the location of a file. Whereas path- and file reference URLs are potentially fragile between launches of an app, a bookmark can usually be used to re-create a URL to a file even in cases where the file was moved or renamed.

To create a bookmark for an existing URL, use the bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error: method of NSURL.

Specifying the NSURLBookmarkCreationSuitableForBookmarkFile option creates an NSData object suitable for saving to disk

Enumerating the Contents of a Directory

To discover the contents of a given directory, we enumerate that directory in two ways.

  1. One file at a time
  2. All at once

→ Example for Saving some images into the disk and retrieving back :

Example for Moving, Deleting and Copying items from and to directories :

FileManager offers a convenient way to create, read, move, copy, and delete both files and directories, whether they’re on local or networked drives or iCloud ubiquitous containers.

You can down load the full source code from this link, and then run on your simulator, to see the directory path on console. Then experiment with the actions how the items being removed, stored, moved, scanned, and fetch back to render in collection view object.

Sources :

  1. NSHipster
  2. iOSbrain.com & iOSbrain.com Tutorial

— — — — — — — — — *********************** — — — — — — — — —

you can contact / follow me on twitter & linkedIn accounts.

Thanks for reading…

****************************!!!See you!!!****************************

--

--