Saving small data when the App is not running (session or other state variables)

We can store any data type in the local storage as long as the App is installed. It means even if the app is not running, small values can be stored in the storage, and the app can access them whenever needed, like from a database. We use UserDefaults for that.

We can store key-value pairs using UserDefaults. For each key, the app can store a value. The value can be of many data types, like Bool, Float, Double, Int, String, URL, etc. You can also write more complex types such as arrays, dictionaries, and Date – and even Data values.

The syntax is very simple. You need to instantiate user defaults by writing something like:

let defaults = UserDefaults.standard

Writing data

You can save data by writing something like:

let valueToBeSaved = "THIS_IS_THE_API_KEY"
defaults.set(valueToBeSaved, forKey: "apiKey")

In the above code, we are saving valueToBeSaved String to the local storage with the key "apiKey." The key is important to retrieve the data.

Reading data

You can read data by accessing something like:

let apiKeySaved = defaults.object(forKey: "apiKey") as! String?
        
if let apiKey = apiKeySaved{
    //MARK: tasks if there is a key saved
    print("The Saved API Key: \(apiKey)")
}else{
    //MARK: tasks if there is no key saved
    print("No API Key saved at the moment!")
}

In the above code, we access the value saved using the key "apiKey."

Please note,

  • You should not be saving heavy data using UserDefaults. It is a slow transaction since the data is saved in the local storage, not in the RAM on your device.

  • You should not use UserDefaults for inter-screen communications.

For more details, please read Paul Hudson's explanations here: https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-userdefaults

Last updated

Was this helpful?