Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

iOS NSUserDefaults Swift Example to Save Data using Xcode 7

August 10, 2016 by Belal Khan Leave a Comment

In this post we will see how we can use iOS NSUserDefaults to save data or application settings. iOS NSUserDefaults is often used to store the application settings. Suppose you need to store some small data in the app like username, gender or any kind of thing that usually doesn’t need a database. In this case you can use iOS NSUserDefaults to save these settings. So lets begin.

What you can store in iOS NSUserDefaults

Though you cannot store everything in NSUserDefaults. These are some common things that you can store using iOS NSUserDefaults.

  • NSData
  • NSString
  • NSNumber
  • NSDate
  • NSArray
  • NSDictionary

If you go in depth then you know that you can store almost anything 😛 . Though still there is some limitation. But lets know how we can write data to iOS NSUserDefaults.

Writing to iOS NSUserDefaults

Writing to NSUserDefaults is very easy. See the following code snippet.

let defaultValues = NSUserDefaults.standardUserDefaults()
defaultValues.setObject("Simplified iOS", forKey: "nameKey")

In the first line we are creating a reference in defaultValues, now this defaultValues can access the NSUserDefaults. Then in the second line we are putting a simple String to the defaultValues. The data are stored in name value pair and the name is passed in the second parameter after forKey: .

These are some more methods to write data in NSUserDefaults

func setBool(value: Bool, forKey defaultName: String)
func setInteger(value: Int, forKey defaultName: String)
func setFloat(value: Float, forKey defaultName: String)
func setDouble(value: Double, forKey defaultName: String)
func setObject(value: AnyObject?, forKey defaultName: String)
func setURL(url: NSURL?, forKey defaultName: String)

Reading from iOS NSUserDefaults

Reading from NSUserDefaults is also very easy. See the following code snippet.

let defaultValues = NSUserDefaults.standardUserDefaults()
if let name = defaultValues.stringForKey("nameKey") {
    //use the name variable here 
}

In the above code again we are creating a reference to NSUserDefaults. And to get the saved name we are using the function stringForKey.

These are some more methods to read data from NSUserDefaults

func boolForKey(defaultName: String) -> Bool
func integerForKey(defaultName: String) -> Int
func floatForKey(defaultName: String) -> Float
func doubleForKey(defaultName: String) -> Double
func objectForKey(defaultName: String) -> AnyObject?
func URLForKey(defaultName: String) -> NSURL?
func dataForKey(defaultName: String) -> NSData?
func stringForKey(defaultName: String) -> String?
func stringArrayForKey(defaultName: String) -> [String]?
func arrayForKey(defaultName: String) -> [AnyObject]?
func dictionaryForKey(defaultName: String) -> [String : AnyObject]?

Now lets see a practical example of reading and writing data using iOS NSUserDefaults.

iOS NSUserDefaults Example Application

Creating a New Xcode Project

So first we will create a new Xcode Project. The process is same as we did in the previous tutorials.

  • Create a Single View iOS App.

ios nsuserdefaults

Adding Views to Storyboard

  • Now click on Main.storyboard and from the right drag Two Button, One Text Field and One Label on the storyboard, as show in the below image. We will use the Label to display the saved name.

ios nsuserdefaults

  • Now we will connect these views to our ViewController.swift file. The process is very simple and we discussed connecting views to swift file in previous tutorials. You can check the previous Xcode Button Tutorial if you don’t know about the connection process.

Writing Data to iOS NSUserDefaults

  • After connecting the views to swift file we can use the above learnt code to save name in NSUserDefaults. See the following code.
//
//  ViewController.swift
//  NSUserDefaultsExample
//
//  Created by Belal Khan on 10/08/16.
//  Copyright © 2016 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    
    
    @IBOutlet weak var textFieldName: UITextField!
    
    @IBAction func buttonClick(sender: UIButton) {
    
        //getting name from text field
        let name = textFieldName.text
        
        //storing to nsuserdefaults
        let defaultValues = NSUserDefaults.standardUserDefaults()
        defaultValues.setObject(name, forKey: "nameKey")
        
        
        //displaying a success alert
        let alertController = UIAlertController(title: "Simplified iOS", message: "Name saved successfully", preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
        alertController.addAction(defaultAction)
        
        presentViewController(alertController, animated: true, completion: nil)
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

  • Now try running your application in simulator.

saving data ios nsuserdefaults

  • So the saving works fine. Lets try reading the saved values from iOS NSUserDefaults.

Reading Data from iOS NSUserDefaults

  • To read values connect the save button and label to your swift code and write the following code.
//
//  ViewController.swift
//  NSUserDefaultsExample
//
//  Created by Belal Khan on 10/08/16.
//  Copyright © 2016 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var labelName: UILabel!
    
    
    @IBOutlet weak var textFieldName: UITextField!
    
    @IBAction func buttonClick(sender: UIButton) {
    
        let name = textFieldName.text
        let defaultValues = NSUserDefaults.standardUserDefaults()
        defaultValues.setObject(name, forKey: "nameKey")
        let alertController = UIAlertController(title: "Simplified iOS", message: "Name saved successfully", preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
        alertController.addAction(defaultAction)
        
        presentViewController(alertController, animated: true, completion: nil)
    
    }
    
    
    
    @IBAction func buttonGet(sender: AnyObject) {
        
        //getting the reference
        let defaultValues = NSUserDefaults.standardUserDefaults()
        
        //getting the name saved
        if let name = defaultValues.stringForKey("nameKey") {
            //displaying the name
            labelName.text = name
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

  • Now again run your app in simulator.

reading data ios nsuserdefaults

  • So its working absolutely fine. If you are having any trouble you can download my source code from the below link.

[sociallocker]  iOS NSUserDefaults Swift Example  [/sociallocker]

So thats all for this iOS NSUserDefaults Swift Example friends. Feel free to leave your comments if having any confusions or doubts regarding this iOS NSUserDefaults Swift Example. Thank You 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: ios nsuserdefaults, nsuserdefaults example swift, nsuserdefaults swift

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift PHP MySQL Tutorial – Connecting iOS App… (94,532)
  • Swift SQLite Tutorial for Beginners – Using… (94,175)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (78,244)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (65,225)
  • Download Full High Sierra Installer to Create Bootable USB (61,246)
  • How to Format USB on Mac? Formatting External Hard… (60,779)
  • Swift JSON Tutorial – Fetching and Parsing… (58,674)
  • Firebase Realtime Database Tutorial for Swift using Xcode (52,001)
  • iOS Registration Form Example using PHP and MySQL (46,976)
  • Xcode Text Field Tutorial for iOS Application using Swift (39,039)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·