Monday, May 15, 2017

Store Data Permanently using UserDefaults

       Hello developers, In this tutorial we're going to learn how to store user's phone number in iOS Apps using UserDefaults(NSUserDefaults) class. If you tried to store huge amount of data using UserDefaults then it'll slow down your app.


What is UserDefaults ?


        For storing a user preference, we want to use UserDefaults this will allow you to store a small amount of datas such as users phone number, user email id and so on. UserDefault can be used to store integers, double, string, booleans, arrays, dictionaries etc. At runtime, it'll read the defaults that your application uses from a user's default database.

        You may noticed in any social messaging app that once you entered the username for the first time then it'll show you again and again when each time the app launches. Okay let's fire up the Xcode and start building our app from scratch.

Creating a Project


  • Open Xcode and Create a new project from the file menu.
  • Select Single View Application template and click Next.
  • Give name to product, organization and organization identifier. See below image for reference.

   

Adding Views 


  • Click the Main.Storyboard file.
  • Drag and drop the Labels, TextField and Buttons from the Object Library into the View. Do like below image.

  • Now open the Assistant Editor in Xcode. Click the double circled icon in top right corner(See the image below) or Click CMD + OPTION + ENTER shortcut.



  • Then drag and drop the labels, textField and buttons into the view controller(viewcontroller.swift file)



  • Then it'll show you one tiny window, in that you've to change the connections and click connect. For button, change the connection from Outlet into Action. For Label, set the connection as Outlets(By default, it's Outlet only). 
  • Note: Here I took screenshots only for label and buttons. So just do the same procedure for textField also and set the connection as Outlet



View Controller Code


    @IBOutlet var phoneNumbLabel: UILabel!
    @IBOutlet var textField: UITextField!
    
    @IBAction func saveBtn(_ sender: Any) {
        
        let phNumb = textField?.text
        
        //Storing phone numbers with userphnumb key
        UserDefaults.standard.set(phNumb, forKey: "userphnumb")
        
        //Retrieving phone numbers from user default database with userphnumb key and it cast it into String because we need to set it as label in our app
        if let retrievedNumb = UserDefaults.standard.object(forKey: "userphnumb") as? String{
            
             print(retrievedNumb)
             phoneNumbLabel.text = retrievedNumb
            
        }
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        if let retrievedVal = UserDefaults.standard.object(forKey: "userphnumb") as? String{
            
            phoneNumbLabel.text = retrievedVal
            
        }
    }



Run the App


      Now build the project and run it. Then the app will open in Simulator.



    In the first time of installation you'll have "Label" text in the right side of "Your number:". Just type the phone number and click the save button(it'll stored in the database) then the "Label" is changed to number what you've typed in the TextField. Then if you close the app and open it again then you'll have your number. Our app fetches the data from the database with the key and it shows to you in the right side of "Your number". This is what the beauty of User Defaults :)

Download this Project

    Guys, I hope you understand about the UserDefaults in Swift. If you have any doubts in this tutorial then just drop your comments right below the post. See you in the next tutorial..

    Happy Coding :)

Location:India, Tamil Nadu, Tuticorin Thoothukudi, Tamil Nadu, India