Local storage Swift UI – CRUD

Local storage means the data that is stored inside the app. You do not need an internet connection to create or read data from local storage. We will create a simple iOS app in Swift UI that allows you to create, read, update, and delete values in local storage. For that, we are going to use a built-in class in Swift called UserDefaults.

Note: UserDefaults class must only be used to store singular values, for example, last_login, name, email, etc. It should NOT be used to store data in the tabular form like MySQL, or in embedded form like Mongo DB.

Local Storage

We will create a simple Swift file named LocalStorage.swift. This file will handle the creating, fetching, updating and deleting the data from local storage.

//
//  LocalStorage.swift
//  Local storage CRUD
//
//  Created by Adnan Afzal on 16/11/2020.
//  Copyright © 2020 Adnan Afzal. All rights reserved.
//

import Foundation

class LocalStorage {
    
    private static let myKey: String = "myKey"
    
    public static var myValue: String {
        set {
            UserDefaults.standard.set(newValue, forKey: myKey)
        }
        get {
            return UserDefaults.standard.string(forKey: myKey) ?? ""
        }
    }
    
    public static func removeValue() {
        UserDefaults.standard.removeObject(forKey: myKey)
    }
    
}

  1. We are creating a static constant named myKey which will hold the name of data.
  2. Then we are creating a static variable named myValue and it has getter and setter. They will automatically be called when we try to save or fetch the value from it.
  3. UserDefaults.standard.string this function returns an optional value, so we have to tell the default value using ?? “”. Here we are setting empty value as default.
  4. Lastly, a static function named removeValue() is created which will remove that value from UserDefaults.

We have made the variables and functions static, so we can use them without creating an object of the LocalStorage class.

You can use the same technique to add as more values as required.

Main Swift UI view

First, we will create a view where we will show 4 buttons to create, view, update, and delete data from UserDefaults. In your main ContentView file, create a navigation view, and inside it create 4 navigation links horizontally.

Right now, we are creating navigation link for AddView only. We will create navigation links for others later in this article.

NavigationView {
    HStack { 
        NavigationLink (destination: AddView(), label: {
            Text("Add")
        })
    }
}
  1. destination: is the view which will be displayed when this navigation link is clicked
  2. label: is the view that will be displayed to the user.

Add value to local storage

Now create a new Swift UI view file named AddView.swift. In this view, we will create an input field and a button which when clicked will save the text field value in local storage.

To get the value from the text field in Swift UI, we will use the @State property wrapper. First, create a @State variable of type String inside your AddView struct:

@State var value: String = ""

Now we can bind this variable in text field’s text value.

VStack {
    TextField("Enter value", text: $value)

    Button(action: {
        LocalStorage.myValue = self.value
    }, label: {
        Text("Save")
    })
}
  1. VStack will show the views vertically.
  2. TextField field is created and its value is bound with our value variable.
  3. Button is created with the text “Save” which when clicked will set the myValue variable from LocalStorage class to our value variable.

The setter inside LocalStorage myValue variable will automatically be called when we assign the value. The code inside setter saves the value in UserDefaults.

Get value from local storage

First, we will create a navigation link in our main view to move to a new view to show value from local storage.

// ContentView.swift

NavigationLink (destination: DataView(), label: {
    Text("View")
})

Now create a new Swift UI view file named DataView.swift. This file will simply fetch the value and show it in text view.

Text(LocalStorage.myValue)

This will automatically called the getter inside LocalStorage myValue variable. The getter is fetching the value from UserDefaults. If the value is not found, then it is setting the default value to empty string.

Edit value in local storage

First, we will create a navigation link in our main view to move to a new view to update the value in local storage.

// ContentView.swift

NavigationLink (destination: EditView(), label: {
    Text("View")
})

Now create a new Swift UI view file named EditView.swift. Editing the value is almost similar to adding the value. But it has 2 steps:

  1. Show the existing value in text field.
  2. Update the value from text field.

Again, we will create a @State property wrapper in this view:

@State var value: String = ""

Then, we will create VStack to show text field and a button vertically. Bound the value variable to text field’s value. Create a button with a text “Update” and setting the local storage value to text field value (same as we did for adding value).

But when the view is loaded, you need to show the existing value in the text field. You can do that by adding an onAppear function to your main view (VStack in my case). In the perform parameter, we will fetch the value from local storage and assign it to our value variable.

As the text field’s text is bound to value variable, so when it’s value is changed, the text field’s text will automatically be changed.

VStack {
    TextField("Enter value", text: $value)
    Button(action: {
        LocalStorage.myValue = self.value
    }, label: {
        Text("Update")
    })
}
.onAppear(perform: {
    self.value = LocalStorage.myValue
})

Delete a value from local storage

We do not need to create a navigation link to delete. We will simply create a button that when clicked will call the function removeValue() from LocalStorage class.

Button(action: {
    LocalStorage.removeValue()
}, label: {
    Text("Delete")
})

Your local storage CRUD operation in Swift UI is done here.

[wpdm_package id=’870′]