loading

Getting Data from UserDefaults

Getting Data from UserDefaults

It’s quite easy to get info from UserDefaults. The getter methods in UserDefaults are the ones listed below.

SNMethodDescription
1func object(forKey: String) -> Any?It returns the object associated with the specified key.
2func url(forKey: String) -> URL?It returns the url associated with the specified key.
3func array(forKey: String) -> [Any]?It returns the array associated with the specified key.
4func dictionary(forKey: String) -> [String : Any]?It returns the dictionary associated with the specified key.
5func string(forKey: String) -> String?It returns the string associated with the specified key.
6func stringArray(forKey: String) -> [String]?It returns the string array associated with the specified key.
7func data(forKey: String) -> Data?It returns the binary data associated with the specified key.
8func bool(forKey: String) -> BoolIt returns the boolean value associated with the specified key.
9func integer(forKey: String) -> IntIt returns the integer value associated with the specified key.
10func float(forKey: String) -> FloatIt returns the float value associated with the specified key.
11func double(forKey: String) -> DoubleIt returns the double value associated with the specified key.
12func dictionaryRepresentation() -> [String : Any]It returns the dictionary representation of the UserDefualts.

Considering that the UserDefaults get the value stored in relation to the key using the data types. It is possible that the value for the given key does not exist. Therefore, in order to retrieve the value from the UserDefaults, we must use the optional binding.

				
					if let token = UserDefaults.standard.string(forKey: "userToken"){  
debugPrint(token)  
        }  
				
			

We use UserDefaults in a singleton Shared Preference class in real-time projects. Now let’s look at an example where we explicitly construct a SharedPreferenceManager class and place all of the user default code inside of it.

SharedPreferenceManager.swift

				
					import Foundation  
  
class SharedPreferenceManager: NSObject {  
    class var sharedIntance : SharedPreferenceManager {  
        struct Static {  
            static let instance = SharedPreferenceManager()  
        }  
        return Static.instance  
    }  
      
    let sharedPreferenc = UserDefaults.standard  
      
    //MARK:- clear all Data.  
    func clearAllPreference() {  
        if let bundle = Bundle.main.bundleIdentifier {  
            sharedPreference.removePersistentDomain(forName: bundle)  
        }  
    }  
      
    //MARK:- setter methods.  
       func saveUserToken (_ userToken : String) {  
        sharedPreference.set(userToken, forKey: "userToken")  
    }  
      
      
    
      
    //MARK:- getter Methods.  
      
    func getUserToken() -> String? {  
        return sharedPreference.value(forKey: "userToken") as? String  
    }  
				
			

ViewController.swift

				
					import UIKit  
  
class ViewController: UIViewController {    
    override func viewDidLoad() {  
        super.viewDidLoad()  
        // Do any additional setup after loading the view.  
        let token = "ABCDEFGD!@#$456MK"  
        SharedPreferenceManager.sharedIntance.saveUserToken(token)  
          
        if let token = SharedPreferenceManager.sharedIntance.getUserToken(){  
            debugPrint(token)  
        }  
     }  
    }  
				
			

A real-time project can make use of the SharedPreferenceManager class, which has all the setter and getter methods needed to store and get data from UserDefaults.

Where to use UserDefaults

Simple data pieces are primarily stored in the UserDefaults. However, using a real database, such as CoreData or SQLite, is preferable if we need to store many items of the same type. A crucial component of your application’s architecture is database design. In the following section of this course, we will learn about CoreData.

Use Cases of using UserDefaults

1. In UserDefaults, we can keep user data such as name, email address, age, and profession.

2. The user’s navigation is determined by the flags recorded in UserDefaults, which we may keep and check in AppDelegate.

3. UserDefaults is where application settings such as color theme, interface language, and so forth can be kept.

4. The UserDefaults is where we can keep the user access token.

Share this Doc

Getting Data from UserDefaults

Or copy link

Explore Topic