There are lots of ways to store data locally in iOS apps.
- For small pieces of data, you can use UserDefaults. It’s a simple key-value store that is easy to use.
- For sensitive data, there’s a keychain. It’s a bit of a pain to use, but there are libraries to make that easier.
- If you need a database then there’s CoreData. It’s quite a high level so even if you don’t know how to use a database you can learn how it works. Or if you want something low level you can use SQLite libraries to access the database directly.
- Or you can just write to the file system the same way you do on a PC.
- And if none of those appeals to you, you could use a third-party library like RealmDB and Firebase Real-time Databases to save your data.
But, We’re using UserDefaults This tutorial will show you how to use UserDefaults in Swift.
What are UserDefaults?
UserDefaults, provided since iOS 2.0, provides an interface for storing persistent values after the application is installed. UserDefaults is similar to a database.As per Apple Documentation, UserDefaults is
An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.
UserDefaults are to be used to store small pieces of data that persist across app launches. It is very common to use UserDefaults to store app settings or user preferences. UserDefaults allows you to store key-value pairs, where a key's always a String and value can be one of the following data types: Data, String, Number, Date, Array, or Dictionary. So we can say that It is structure is similar to that of a dictionary that uses key-value pair.
let dict = [ "name": "Praksh Singh", "empCode": "2058740", "role": "Developer", "team": "Development" ] print(dict["role"]!) // Developer
How to use UserDefaults in Swift?
First, create the standard user defaults object and Set the UserDefaults, use one of its set(_:forKey:) instance methods which are String, boolean, double, integer, and set URL.
//*******Saving Data in UserDefaults******* let defaults = UserDefaults.standard defaults.set("Praksh Singh", forKey: "name") defaults.set(true, forKey: "userlogin") defaults.set(CGFloat.pi, forKey: "Pi") defaults.set(2058740, forKey: "empCode") defaults.set("https://www.appcodezip.com", forKey: "homeURL")
Now, you can use Get data from UserDefaults.These method are string(forKey:),bool(forKey:),double(forKey:), integer(forKey:)and url(forKey:).
//*******Getting Data from UserDefaults******* let name = defaults.string(forKey: "name") print(name ?? "Unknown user") let login = defaults.bool(forKey: "userlogin") print(login) let pi = defaults.double(forKey: "Pi") print(pi) let empCode = defaults.integer(forKey: "empCode") print(empCode) let url = defaults.url(forKey: "homeURL") print(url ?? "www.appcodezip.com")
Set the value of “saveFruits” key to an array of strings & Set the value of "SaveDict " to a Swift dictionary. where Get data from UserDefaults, use one of its type dedicated get methods object(forKey:)method.These method are array(forKey:) & dictionary(forKey:).
//*******Saving Array & Dictionary Data in UserDefaults******* let defaults = UserDefaults.standard let arrFruits = ["Apple", "Blackberries","Banana","Mango","Cherries"] defaults.set(arrFruits, forKey: "saveFruits") let dict : [String: String] = [ "name": "Praksh Singh", "empCode": "2058740", "role": "Developer", "Team": "Development" ] defaults.set(dict, forKey: "SaveDict") //*******Getting Data from UserDefaults******* let fruitsArray = defaults.array(forKey: "saveFruits") ?? [String]() print(fruitsArray) let dictData = defaults.dictionary(forKey: "SaveDict") as? [String: String] ?? [String: String]() print(dictData)
Here we can use object(forKey:) and as? to get an optional object, then use ?? to either unwrap the object or set a default value in single line.
removeObject(forKey:) to remove the value from userdefault.
let defaults = UserDefaults.standard defaults.set(true, forKey: "userlogin") let login = defaults.bool(forKey: "userlogin") print(login) //true print(defaults.removeObject(forKey: "userlogin")) //()
Where is UserDefaults stored?
Internally user defaults are saved in a .plist file where, plist is short for property list. This is usually an info.plist file created for you when you start new iOS project. A property list file is a dictionary saved in a row-column format, like this:
How much data can be stored in UserDefaults?
UserDefaults saves its data in a local plists file in your app’s project. UserDefaults are persisted for backups and restores. Currently there is no size limit for data on platforms.But storing large amounts of data in UserDefaults may severely affect the performance of the application, because the entire UserDefaults plist file is loaded into memory when the application is started.So used to small pieces of data.As per Apple Documentation...
Currently, there is only a size limit for data stored to local user defaults on tvOS, which posts a warning notification when user defaults storage reaches 512kB in size, and terminates apps when user defaults storage reaches 1MB in size.
When you store data in UserDefaults. The UserDefaults plist is saved data in the Library folder inside the app folder.
One Example to find the library folder in the app where data is saved. we set the value of "homeURL" and "userlogin"and find the librarypath
let defaults = UserDefaults.standard defaults.set("https://www.appcodezip.com", forKey: "homeURL") defaults.set(true, forKey: "userlogin") let library_path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] print("App Library Path is \(library_path)") }
Build and run the app, then open Finder and press command + shift + G , paste in the library path and click 'Go' to navigate to the Library folder.
You will see hierarchy folder of 'Preferences' , the UserDefaults plist file is stored inside the 'Preferences' folder.
double click the .plist file, Xcode will show a property list format
As UserDefaults uses .plist format to save data, we can only store data with type of NSString, NSNumber, NSData, NSArray, NSDictionary or NSData.
When to Use UserDefaults?
UserDefaults can be used as a convenient way to save a small amount of available data, even if you close the application and restart it.You can use UserDefaults for storing user settings (eg: settings page in your app with UISwitch, Segmented Control, simple Textfield, User information, or flag) If you need to store big data or access it through complex queries, you may need to use SQLite, Core Data ,RealmDB and Firebase Real-time Databases.
Thank you for reading!
Similar solutions you may also like...
Memory Management with ARC and Avoiding retain cycles with Weak and Unowned in Swift.
How to generate .ipa file for In-House and distribute enterprise iOS app inside a company
Memory Management with ARC and Avoiding retain cycles with Weak and Unowned in Swift.
Swift 5.2 Generics Explained - How to Use Generics in iOS Apps
0 Comments