Use Settings with NSUserDefaults in iOS8 with Swift

With the NSUserDefaults 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 built in iOS 8 and Xcode 6.1

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftNSUserDefaultsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and drag a Label to the left side of the view. Select the Label and give it a tile 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: AnyObject) {
    var defaults = NSUserDefaults.standardUserDefaults()
    if bluetoothSwitch.on {
        defaults.setBool(true, forKey: "SwitchState")
    } else {
        defaults.setBool(false, forKey: "SwitchState")

We create a NSUserDefaults 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() {
    var defaults = NSUserDefaults.standardUserDefaults()
    if (defaults.objectForKey("SwitchState") != nil) {
        bluetoothSwitch.on = defaults.boolForKey("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 IOS8SwiftNSUserDefaultsTutorial at the ioscreator repository on Github.