Easy way to save the class object in local storage, user defaults - Swift

Easy way to save the class object in user defaults – Swift iOS

When it comes to saving the class object in user defaults, there is a hard way to do using NSKeyedArchiver class. But there is an easy to do using JSONEncoder and JSONDecoder classes. In this tutorial, we will teach you how you can:

  1. Save the class object in user defaults using Swift by encoding in JSON.
  2. Get a class object from user defaults by decoding from JSON.
  3. Remove the class object from user defaults.

First create a model class in Swift which will be the class that needs to be stored in user defaults.

User.swift

import Foundation

class User: Codable {
    public var id: Int = 0
    public var name: String = ""
}

Make sure it is a type of Codable protocol, this will help to convert the class into JSON. Set the default values to all data members, integers to 0, and strings to empty string. Then we will create a file which will have all the functions to save, retrieve, and remove the class object value from user defaults, we name that class LocalStorageManager.

LocalStorageManager.swift

import Foundation

class LocalStorageManager {
    
    public func saveUser(user: User) {
        do {
            
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(user)
            let json = String(data: jsonData, encoding: .utf8) ?? "{}"
            
            let defaults: UserDefaults = UserDefaults.standard
            defaults.set(json, forKey: "user")
            defaults.synchronize()
            
        } catch {
            print(error.localizedDescription)
        }
    }
    
    public func getUser() -> User {
        do {
            if (UserDefaults.standard.object(forKey: "user") == nil) {
                return User()
            } else {
                let json = UserDefaults.standard.string(forKey: "user") ?? "{}"
                
                let jsonDecoder = JSONDecoder()
                guard let jsonData = json.data(using: .utf8) else {
                    return User()
                }
                
                let user: User = try jsonDecoder.decode(User.self, from: jsonData)
                return user
            }
        } catch {
            print(error.localizedDescription)
        }
        return User()
    }
    
    public func removeUser() {
        let defaults: UserDefaults = UserDefaults.standard
        defaults.removeObject(forKey: "user")
        defaults.synchronize()
    }
}
  1. Create a global data member that will be the key used to identify the object in user defaults.
  2. saveUser function will receive the User class instance as a parameter, convert that as JSON string and save in user defaults.
  3. getUser function will return the user class instance by decoding from the JSON string. Here, we will handle all the validations that might be useful for decoding the JSON data.
  4. removeUser function is used to delete the user class instance from user defaults.

To use this, we are going to simply call these functions from our main view controller file.

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let user: User = User()
        user.id = 565
        user.name = "Adnan"
        
        LocalStorageManager().saveUser(user: user)
        
        let cacheUser: User = LocalStorageManager().getUser() 
        print(cacheUser)
        
        LocalStorageManager().removeUser()
        
        let cacheUserAgain: User = LocalStorageManager().getUser() 
        print(cacheUserAgain)
    }
}
  1. First we are creating an instance of user class and set the values.
  2. Then we are saving in user defaults.
  3. After that, we are retrieving the saved user class object and printing it out for debugging.
  4. Finally, we are removing it from user defaults and printing it out.

Leave a Reply

Please disable your adblocker or whitelist this site!