Tuesday 27 June 2017

STORE PERMANENT DATA USING UserDefaults( like android shared pref)



STEP-1 : Add three view (TextField, Button, Label) to Main.Storyboard.

STEP-2 : Make reference of view to CiewController.swift
           
TextField. --> input. (@IBOutlet)
Button      -->. Action (@IBAction)
Label.      -->. output (@IBOutlet)


STEP-3 : ViewController.swift


//
//  ViewController.swift
//  StoringData
//
//  Created by Admin on 27/06/17.
//  Copyright © 2017 Admin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var input: UITextField!
    @IBOutlet weak var output: UILabel!
    
    @IBAction func action(_ sender: Any) {
        
        output.text = input.text
        UserDefaults.standard.set(input.text, forKey: "myName")
        input.text = ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(_ animated: Bool) {
        
        if let x = UserDefaults.standard.object(forKey: "myName") as? String
        {
            output.text = x
        }
    }


}


No comments:

Post a Comment