How to save local data in a Swift app?

Nicklas Ridewing picture Nicklas Ridewing · Feb 20, 2015 · Viewed 161.3k times · Source

I'm currently working on a iOS app developed in Swift and I need to store some user-created content on the device but I can't seem to find a simple and quick way to store/receive the users content on the device.

Could someone explain how to store and access local storage?

The idea is to store the data when the user executes an action and receive it when the app starts.

Answer

Wez picture Wez · Feb 20, 2015

The simplest solution if you are just storing two strings is NSUserDefaults, in Swift 3 this class has been renamed to just UserDefaults.

It's best to store your keys somewhere globally so that you can reuse them elsewhere in your code.

struct defaultsKeys {
    static let keyOne = "firstStringKey"
    static let keyTwo = "secondStringKey"
}

Swift 3.0, 4.0 & 5.0

// Setting

let defaults = UserDefaults.standard
defaults.set("Some String Value", forKey: defaultsKeys.keyOne)
defaults.set("Another String Value", forKey: defaultsKeys.keyTwo)

// Getting

let defaults = UserDefaults.standard
if let stringOne = defaults.string(forKey: defaultsKeys.keyOne) {
    print(stringOne) // Some String Value
}
if let stringTwo = defaults.string(forKey: defaultsKeys.keyTwo) {
    print(stringTwo) // Another String Value
}

Swift 2.0

// Setting

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Some String Value", forKey: defaultsKeys.keyOne)
defaults.setObject("Another String Value", forKey: defaultsKeys.keyTwo)

// Getting

let defaults = NSUserDefaults.standardUserDefaults()
if let stringOne = defaults.stringForKey(defaultsKeys.keyOne) {
    print(stringOne) // Some String Value
}
if let stringTwo = defaults.stringForKey(defaultsKeys.keyTwo) {
    print(stringTwo) // Another String Value
}

For anything more serious than minor config, flags or base strings you should use some sort of persistent store - A popular option at the moment is Realm but you can also use SQLite or Apples very own CoreData.