How do I use UserDefaults in Swift iOS?

Article by: Manish Methani

Last Updated: October 2, 2021 at 8:04am IST
7 min 6 sec read

Suppose you want to store some data which you think will be useful throughout your app and you want to save it then NSUserDefualts Class is the most easiest way to save application data and properties. Even if you close your application that saved data will be available to you throughout your app. You might think where this data will be stored . Right ? The objects will be saved in what is known as the iOS "defaults system ".

With NSUserDefaults you can save objects from following class types :

 

1) NSNumber

2) NSDictionary

3) NSArray

4) NSData

5) NSDate

Example :-

In this example, you will learn how to use NSUserDefaults in Swift. We save string value of name , integer value of age and image in NSUserDefaults for example(say).

1) Create a new Xcode Project, File > New > Project > Single View Application > Enter Project Name > Create

 

 

2) Now copy this code in ViewController.swift file to create User Interface for sample App

import UIKit

class ViewController: UIViewController ,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
    var labelUserDefaults = UILabel()
    var textFieldName = UITextField()
    var textFieldAge = UITextField()
    var buttonSave = UIButton()
    var imageButton = UIButton()
    var imageUser = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        labelUserDefaults = UILabel.init(frame: CGRect(x: self.view.frame.midX - 60 , y: 40 , width: self.view.frame.size.width , height: 28) );
        self.view.addSubview(labelUserDefaults)
        labelUserDefaults.text = "NSUserDefaults in Swift | iOS App development"
        labelUserDefaults.textColor = UIColor.init(red: 38.0/255.0, green: 84.0/255.0, blue: 162/255, alpha: 1.0);
        labelUserDefaults.font = UIFont.init(name: "helvetica-bold", size: 20.0)
        
        
        
        imageButton = UIButton.init(frame: CGRect(x: 40 , y: labelUserDefaults.frame.maxY + 12 , width: 120 , height: 120) );
        self.view.addSubview(imageButton)
        imageButton.addTarget(self, action: #selector(self.imageButtonClicked), for: UIControlEvents.touchUpInside)
        imageButton.layer.borderWidth = 1.0;
        imageButton.layer.cornerRadius = 3.0
        
        
        imageUser = UIImageView.init(frame: CGRect(x: 40 , y: 40 , width: 40 , height: 40) );
        imageButton.addSubview(imageUser)
        imageUser.image = UIImage.init(named: "camera");
        
        
        textFieldName = UITextField.init(frame: CGRect(x: imageButton.frame.maxX + 20 , y: labelUserDefaults.frame.maxY + 12 , width: 180 , height: 32) );
        self.view.addSubview(textFieldName)
        textFieldName.placeholder = "Name"
        textFieldName.font = UIFont.init(name: "Helvetica-bold", size: 13.0)
        textFieldName.layer.borderWidth = 1.0
        textFieldName.layer.cornerRadius = 3.0
        textFieldName.layer.borderColor = UIColor.gray.cgColor
        textFieldName.textAlignment = NSTextAlignment.center
        textFieldName .becomeFirstResponder()
        
        
        textFieldAge = UITextField.init(frame: CGRect(x: imageButton.frame.maxX + 20 , y: textFieldName.frame.maxY + 12 , width: 180 , height: 32) );
        self.view.addSubview(textFieldAge)
        textFieldAge.placeholder = "Age"
        textFieldAge.font = UIFont.init(name: "Helvetica-bold", size: 13.0)
        textFieldAge.layer.borderWidth = 1.0
        textFieldAge.layer.cornerRadius = 3.0
        textFieldAge.layer.borderColor = UIColor.gray.cgColor
        textFieldAge.textAlignment = NSTextAlignment.center
        textFieldAge .becomeFirstResponder()
        
        
        
        
        buttonSave = UIButton.init(frame: CGRect(x: imageButton.frame.maxX + 20 , y: textFieldAge.frame.maxY + 12 , width: 180 , height: 32) );
        self.view.addSubview(buttonSave)
        buttonSave.addTarget(self, action: #selector(self.saveButtonClicked), for: UIControlEvents.touchUpInside)
        buttonSave.layer.borderWidth = 1.0;
        buttonSave.layer.cornerRadius = 3.0
        buttonSave.backgroundColor = UIColor.init(red: 38.0/255.0, green: 84.0/255.0, blue: 162/255, alpha: 1.0);
        buttonSave.setTitleColor(UIColor.white, for: UIControlState.normal)
        buttonSave.setTitle("Save Data", for: UIControlState.normal)
    
    self.prepopulateData()
    }
    
    
    func prepopulateData()
    {
      let userDefaults = UserDefaults.standard
      textFieldAge.text =  userDefaults.value(forKey: "age") as! String?
       textFieldName.text = userDefaults.value(forKey: "name") as! String?
        
        
        let imageData = userDefaults.data(forKey: "image")
        let imageUs = UIImage.init(data: imageData!)
        imageButton.setImage(imageUs, for: UIControlState.normal)
        imageUser.image = imageUs
    }
    
    func saveButtonClicked()
    {
        let imageUs = imageUser.image
        let imageData = UIImageJPEGRepresentation(imageUs!, 100)
        
    let userDefaults = UserDefaults.standard
    userDefaults.setValue(textFieldName.text, forKey: "name")
        userDefaults.set(textFieldAge.text, forKey: "age")
        userDefaults.set(imageData, forKey: "image")
       
        let alert = UIAlertController(title: "Alert", message: "Data Saved Successfully", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

    func imageButtonClicked()
    {
        let actionSheet = UIActionSheet(title: "", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Gallery", "Camera")
        
        
        actionSheet.show(in: self.view)
    }
    
    func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int)
    {
        switch (buttonIndex){
            
        case 1:
            self.galleryPressed()
            break;
        case 2:
           self.cameraPressed()
           break;
            
        default:
            break;
        }
    }
    
    func galleryPressed()
    {
     let imagePickerController = UIImagePickerController()
       imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePickerController.allowsEditing = true
        imagePickerController.delegate = self
        self.present(imagePickerController, animated: true, completion: nil)
        
    }
    
    func cameraPressed()
    {
        
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
        imagePickerController.allowsEditing = true
        imagePickerController.delegate = self
        self.present(imagePickerController, animated: true, completion: nil)

    }
   
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
        imageUser.contentMode = .scaleAspectFit //3
        imageButton.setImage(chosenImage, for: UIControlState.normal)
        imageUser.image = chosenImage //4
        dismiss(animated:true, completion: nil) //5
    }
}

3) Output :-

 

Short explanation of code:-

 

In viewDidLoad method we created two textFields, one ImageButton and one save button. When user clicks save button NSUserDefaults reference is created. Then we stored textFieldName's text value with key "name". textFieldAge's integer value inside key "age" and image with the help of imageData in key image

 func saveButtonClicked()
    {
        let imageUs = imageUser.image
        let imageData = UIImageJPEGRepresentation(imageUs!, 100)
        
    let userDefaults = UserDefaults.standard
    userDefaults.setValue(textFieldName.text, forKey: "name")
        userDefaults.set(textFieldAge.text, forKey: "age")
        userDefaults.set(imageData, forKey: "image")
       
        let alert = UIAlertController(title: "Alert", message: "Data Saved Successfully", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

Now to get the stored value from NSUserDefaults we used stringForKey method to get name, integerForKey to get age and dataForKey to get imageData. tehn assigned those value to their respective textFields and imageView.

func prepopulateData()
    {
      let userDefaults = UserDefaults.standard
      textFieldAge.text =  userDefaults.value(forKey: "age") as! String?
       textFieldName.text = userDefaults.value(forKey: "name") as! String?
        
        
        let imageData = userDefaults.data(forKey: "image")
        let imageUs = UIImage.init(data: imageData!)
        imageButton.setImage(imageUs, for: UIControlState.normal)
        imageUser.image = imageUs
    }

At the first time when you try to select an image from the gallery by clicking image button, there are chances that your app may crash. This is because you did not give the permissions to your app to use Library or Camera. So search for .plist file in Xcode and paste this

For Photo Library,
In key column paste this,
Privacy - Photo Library Usage Description

Select type  String

In Value column ,
$(PRODUCT_NAME) photo use
 
For Camera Use,
In key column paste this,
Privacy - Camera Usage Description

Select type  String


In Value column ,
$(PRODUCT_NAME) camera use
 

Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com