Generic Local Persistence
GenericLocalPersistence is a clean and easy-to-use code that is useful for integrating local storage like,
- UserDefaults
- PList
- Keychain
In this article, I am going to explain to you the local persistence available in iOS and its easy usage with the available pod.
Storing data into the local can be the basic requirement of any application. In iOS for storing a huge amount of data locally we have options like Sqlite or the Core database but when it comes to storing the small amount of values/Data or the secret chunks like password, bank account details, etc… we also have some other options available in iOS like UserDefaults, Keychain, and PList.
Instead of writing the same business logic code in projects every time, Using the GenericLocalPersistence you don’t need to create or configure the files and method every time. Install the pod and directly use the defined methods of any of this local Persistence to store and fetch data with any data type.
Let’s see how it is working. Let’s Start…!!!
How does Installation work? 🤔🤔🤔
Create an Xcode project
Form cocoa pods or git, install the pod in a project like below
pod install 'GenericLocalPersistence', '~> 0.0.1’pod 'GenericLocalPersistence', :git => 'https://github.com/Riddhi-mi/GenericLocalPersistence.git'
Once you install the pod you can see the below folder structure in your project inside the pod project
Inside GenericLocalPersistence there are three different Manager DefaultManager, KeyChainManager, and PlistManager.
All this manager will contain the code and method that accept and retrieve generic data type values. So, it will reduce the task of creating files and methods every time while creating the project.
Let’s see how the manager inside the pod will work
Usage of UserDefault
It is very common to use UserDefaults to store app settings or user preferences. UserDefaults lets you store key-value pairs, where a key is always a string and value can be one of the following data types: Data, String, Number, Date, Array, or Dictionary. It will save data on the device disk.
import GenericLocalPersistence
Set & Get value from User Default
Set string Value inside the userDefaultDefaultManager().saveValueInDefault(value: "TestValue", using: "TestKey")Retrive value from the userdefaultlet valueFetch:String = DefaultManager().getValue("TestKey") ?? ""
Note: You can store any data type value from Double, Int, and others by replacing the “TestValue” in saveValueInDefault method.
It will also allow you to store the model class value in UserDefault. Create your own model class and its object. Assing values to the object parameters and you can pass the object directly to the DefaultManager() saveValueInDefault method.
let defultData = DefaultSample()defultData.name = "user"defultData.email = "user@MI.com"defultData.address = "userAddress"DefaultManager().saveValueInDefault(value: defultData, using: "classValues")
Follow the code to get the stored value,
let classVales :DefaultSample = DefaultManager().getValue("classValues") ?? DefaultSample()
print("Address:- \(classVales.address ?? "") Name:- \(classVales.name ?? "") Email:-\(classVales.email ?? "")"
OutPut
Retrieval of data must require a data type in which you want to capture your stored data.
Usage of Plist
PList known as Property List is a flexible and convenient format for storing application data.
First,
import GenericLocalPersistence
Set & Get value from PList file
Create an object of PListManager like,
private let managerPlist = plistManager(named: "userDetails")
Instead of “userDetails” write any name that you wanted to assing for your plist file.
Store data to plist
managerPlist?.saveDatatoPlist(value: "TestString", using: "stringValue")Get string value from plistlet stringValue :String = managerPlist?.getDictionary(key: "stringValue") ?? ""print(stringValue)
Another example of storing data into the PList in form of a dictionary using Model class
let defultData = DefaultSample()
defultData.name = "user"
defultData.email = "user@gmail.com"
defultData.address = "userAddressSample"managerPlist?.saveDatatoPlist(value: defultData, using: "userData")Retrive the same data from plistlet data:NSDictionary = managerPlist?.getDictionary(key: "userData") ?? NSDictionary()defultData = defultData.toDict(data)
this will store the data in form of a dictionary and retrieve it the same way in which you can convert to your model class as per your need.
Where to find the PList with the name “userDetails”??
To find a created plist file, you can write and print
print(managerPlist?.defaultPath() ?? “”)
Which will give you the path of your created plist file.
Go to the path and open the created PList file and you will find the stored data with keys and values…!!!
Usage of KeyChain
The keychain is the best place to store small secrets, like passwords and cryptographic keys, accounts number. You use the functions of the keychain services API to add, retrieve, delete, or modify keychain items.
First,
import GenericLocalPersistence
Set & Get value from KeyChain file
Store password value
let passWordString = textPassword?.text?.data(using: .utf8, allowLossyConversion: false) ?? Data()
let passwordStatus = KeyChainManager()?.save(key: "com.appBundleID.password", data: passWordString)//Retrive dataif let receivedData = KeyChainManager()?.load(key: "com.appBundleID.password") {
let data = String(decoding: receivedData, as: UTF8.self)
print("result: ", data)
}
To Store, the value in KEYCHAIN need a unique ID like “com.appBundleID.password” and “com.appBundleID.email”
Store username value
let userNameString = textName?.text?.data(using: .utf8, allowLossyConversion: false) ?? Data()
let emailStatus = KeyChainManager()?.save(key: "com.appBundleID.email", data: userNameString)//Retrive dataif let data = KeyChainManager()?.load(key: "com.appBundleID.email") {
let data = String(decoding: data, as: UTF8.self)
print("result: ", data)
}
Conclusion
If you have any queries or questions then you can comment here. Also, check out some of the amazing work that we do at MindInventory and how we help build awesome products for people around the world. 😀
You can download the source code from the below link.
Happy Coding…!!!😊😊