Saving and Reading Preferences in Android and iOS

Apps and programs need to set settings or preferences that can be retrieved anytime to customize app look and behavior.  In this article, we will look at how to do it in Android as well as iOS. We can store various types of user settings like integers, floats, bool, string, dictionaries, arrays etc. Avoid storing too many settings as it may slow down app launch.

For Android, we will use Kotlin and for iOS, we will use Swift.

Settings/Preferences in Android

Preferences in android can be set as follows. Following snippet shows how to save string preference. In android, we can set values of types String, Integer, Boolean, Float, Long and String Set.

Reading preferences in Android

Preferences can be read back as follows. We need to provide default return values in case preference with that key is not set.

Settings/Preferences in iOS

Settings or preferences are also called User Defaults in iOS. First we have create defaults object and then use it as follows.

We can also set arrays and dictionaries as iOS app user defaults.

Reading userDefaults in iOS

User defaults can be used using key as shown below by storing them in a variable.

Remember that when reading back user defaults, system may return a default value if that userDefault is not set. Default values as as per type of userDefault.

  • integer(forKey:) returns an integer if the key existed, or 0 if not.
  • bool(forKey:) returns a boolean if the key existed, or false if not.
  • float(forKey:) returns a float if the key existed, or 0.0 if not.
  • double(forKey:) returns a double if the key existed, or 0.0 if not.
  • object(forKey:) returns AnyObject? so you need to conditionally typecast it to your data type.

When retrieving objects, the result is optional. This means you can either accept the optionality, or typecast it to a non-optional type and use the nil coalescing operator to handle missing values. For example: