Member-only story

iOS Data Storage: How to save/read local data in App?

Various methods to store/read data in iOS App

--

In this tutorial, We are going to learn ways to read, write, store data.

Bundle

A simple understanding is the resource file package, which will organize many pictures, xibs, and text files together and package them into a Bundle file. A main bundle get packaged with App. There can be separate bundle for individual library used in app.

//Access the main bundlelet bundle = Bundle.main
let jsonFile = Bundle.main.path(forResource: “xxx”, ofType: “json”)

**Every time when user update app the main bundle also gets an update.

Sandbox

In a Non-Rooted iPhone/iPad device, An App can only perform file operations in the file system created by itself, and cannot access the file system of other apps. The file system becomes a sandbox. All not binary file i.e. asset files can be saved here, such as images, icons, sounds, plists, text, json files.

**This mechanism helps apple to ensure security, So that no app can read/write data without any specific permission.

You can access the root directory of sandbox like following:

let directory = NSHomeDirectory()

Documents directory — save persistent data

Save the Persistent data generated when the application is running.

Getting Path

// Accessing document directory
///Getting Path
///1
let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentPath = documentPaths.first
///2
let documentPath2 = NSHomeDirectory() + “/Documents”

Getting URL Path:

`let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
let url: URL = urlForDocument[0]

**by default all the files in directory get uploaded to iCloud and get shared between different instances of app with common iCloud. To disable this, We need to do following:

var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true ///set true to not backup
try

--

--

Prafulla Singh
Prafulla Singh

No responses yet