UserDefaults iOS Tutorial

With the UserDefaults class, you can save settings and properties related to application or user data. Any data saved to the defaults system will persist through application restarts. In this tutorial we will save the state of a switch, so this state is saved when the app restarts. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use iOSUserDefaultsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag a Label to the left side of the view. Select the Label and give it a title of "Bluetooth". Next, drag a Switch Next to the Label. The Storyboard will look like this

Build and Run, and change the switch to Off. Exit the application and start it again. As you can see the previously selected state isn't persistent through application restarts.


Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Switch to the ViewController class  and create the following Outlet.

Ctrl and drag from the Switch to the ViewController class  and create the following Action.

Go to the ViewController.swift file and implement the saveSwitchState method

@IBAction func saveSwitchState(_ sender: Any) {
    let defaults = UserDefaults.standard
        
    if bluetoothSwitch.isOn {
        defaults.set(true, forKey: "SwitchState")
    } else {
        defaults.set(false, forKey: "SwitchState")
    }
}

We create a UserDefaults object, where we can save the user settings. Next, we save the current switch state as a Boolean value in the Switchstate key. Next, change the viewDidLoad method

override func viewDidLoad() {
    super.viewDidLoad()
        
    let defaults = UserDefaults.standard
        
    if (defaults.object(forKey: "SwitchState") != nil) {
        bluetoothSwitch.isOn = defaults.bool(forKey: "SwitchState") 
    }
}

We check if there is a previously created SwitchState key, and if so we load the state and change the switch. Build and Run, change the switch state to Off. Restart the application and you will see the switch still is in the off state.

You can download the source code of the IOSUserDefaultsTutorial at the ioscreator repository on Github.