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.

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.

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()

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
fileUrl.setResourceValues(resourceValues)

Store the default settings and other information of the program, under which there are two important directories:

  • Library/Preferences directory: Contains application preference settings files. You should not create preference files directly, but rather use UserDefaults classes to get and set application preferences.
  • Library/Caches directory: Store Caches Files in this directory will not be deleted when the application exits.

Accessing Library directory

Getting Path

///1
let libraryPaths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
let libraryPath = libraryPaths[0]
///2
let libraryPath2 = NSHomeDirectory() + “/Library”
/*Cache*////1
let cachePaths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
let cachePath = cachePaths[0]
// 2
let cachePath2 = NSHomeDirectory() + “/Library/Caches”
  • Temporary directory: store temporary files. When exiting the program or restarting the device, the files will be cleared.
///1
let tmpDir = NSTemporaryDirectory()
///2
let tmpDir2 = NSHomeDirectory() + “/tmp”

Read Plist:

if let path = Bundle.main.path(forResource: “cityData”, ofType: “plist”) {
let root = NSDictionary(contentsOfFile: path)
print(root!.allKeys)
}

Write Plist:

do {
let dictionary = [“name” : “prafulla”, “age”:”28", “country”:”Singapore”]
let plistData = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)
try plistData.write(to: plistURL)
} catch {
print(error)
}
  • Generally used to save lightweight data such as user name version, local user choices, etc.
  • Use UserDefaults to set and read preferences.
  • Preferences key-value are read and written in a way.
  • By default, the data is automatically stored in the sandbox’s Library/Preferences directory in plist format.

Working with Preferences:

UIKit:

///Write Data:userDefault = UserDefaults.init()
userDefault.set(“myData”, forKey: “keyForMyData”)
userDefault.syncronize() //save to disk
///Read Data:
let data = userDefault.object(forKey: “keyForMyData”)

SwiftUI:

@AppStorage(“keyForMySharableData”) var username: String = “mySharableData”
/// use username to read write data

Cross-domain:

Follow this detailed article.

iOS Developer | Swift | Flutter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store