Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

Article

How to save data using Userdefaults in Swift 4?

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 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 about 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 the following  class types :

1) NSNumber

2) NSDictionary

3) NSArray

4) NSData

5) NSDate

Example:-

In this example, you will learn how to save the data in NSUserDefaults in Swift. We save the string value of namethe 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 a 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:-

 

A short explanation of code:-

In the viewDidLoad method, we created two text fields, one ImageButton and one save button. When the user clicks the save button NSUserDefaults reference is created. Then we stored textFieldName's text value with key "name"textFieldAge'sinteger value inside key "age" and image with the help of image data in the 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 the stringForKey method to get name, integerForKey to get age, and dataForKey to get imageData. then assigned those values to their respective text fields 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
    }

The first time when you try to select an image from the gallery by clicking the image button, there are chances that your app may crash. This is because you did not give the permissions to your app to use the Library or Camera. So search for .plistfile 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
 

Recommended Articles

Articles you would love to read

How to create a custom tableView cell programmatically in Swift iOS?

Building an App with only code using Autolayout in Swift iOS

Building an App with only code using Autolayout in Swift iOS

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor