iosswiftnsuserdefaults

How to save local data in a Swift app?


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.


Solution

  • The simplest solution for storing a few strings or common types is UserDefaults.

    The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.

    UserDefaults lets us store objects against a key of our choice, It's a good idea to store these keys somewhere accessible so we can reuse them.

    Keys

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

    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

    In Swift 2.0 UserDefaults was called NSUserDefaults and the setters and getters were named slightly differently:

    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 you should consider using a more robust persistent store: