How can I use UserDefaults in Swift? How can I use UserDefaults in Swift? ios ios

How can I use UserDefaults in Swift?


ref: NSUserdefault objectTypes

Swift 3 and above

Store

UserDefaults.standard.set(true, forKey: "Key") //BoolUserDefaults.standard.set(1, forKey: "Key")  //IntegerUserDefaults.standard.set("TEST", forKey: "Key") //setObject

Retrieve

 UserDefaults.standard.bool(forKey: "Key") UserDefaults.standard.integer(forKey: "Key") UserDefaults.standard.string(forKey: "Key")

Remove

 UserDefaults.standard.removeObject(forKey: "Key")

Remove all Keys

 if let appDomain = Bundle.main.bundleIdentifier {UserDefaults.standard.removePersistentDomain(forName: appDomain) }

Swift 2 and below

Store

NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")NSUserDefaults.standardUserDefaults().synchronize()

Retrieve

  var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]

Remove

 NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")


Register

registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.

Default values from Defaults Configuration Files will automatically be registered.

for example detect the app from launch , create the struct for save launch

struct DetectLaunch {static let keyforLaunch = "validateFirstlunch"static var isFirst: Bool {    get {        return UserDefaults.standard.bool(forKey: keyforLaunch)    }    set {        UserDefaults.standard.set(newValue, forKey: keyforLaunch)    }}}

Register default values on app launch:

UserDefaults.standard.register(defaults: [        DetectLaunch.isFirst: true    ])

remove the value on app termination:

func applicationWillTerminate(_ application: UIApplication) {    DetectLaunch.isFirst = false}

and check the condition as

if DetectLaunch.isFirst {  // app launched from first}

UserDefaults suite name

another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here :

The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.

let user = UserDefaults(suiteName:"User")

use of userDefaults synchronize, the detail info has added in the duplicate answer.


Best way to use UserDefaults

Steps

  1. Create extension of UserDefaults
  2. Create enum with required Keys tostore in local
  3. Store and retrieve the local data wherever you want

Sample

extension UserDefaults{    //MARK: Check Login    func setLoggedIn(value: Bool) {        set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue)        //synchronize()    }    func isLoggedIn()-> Bool {        return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue)    }    //MARK: Save User Data    func setUserID(value: Int){        set(value, forKey: UserDefaultsKeys.userID.rawValue)        //synchronize()    }    //MARK: Retrieve User Data    func getUserID() -> Int{        return integer(forKey: UserDefaultsKeys.userID.rawValue)    }}

enum for Keys used to store data

enum UserDefaultsKeys : String {    case isLoggedIn    case userID}

Save in UserDefaults where you want

UserDefaults.standard.setLoggedIn(value: true)          // StringUserDefaults.standard.setUserID(value: result.User.id!) // String

Retrieve data anywhere in app

print("ID : \(UserDefaults.standard.getUserID())")UserDefaults.standard.getUserID()

Remove Values

UserDefaults.standard.removeObject(forKey: UserDefaultsKeys.userID) 

This way you can store primitive data in best

UpdateYou need no use synchronize() to store the values. As @Moritz pointed out the it unnecessary and given the article about it.Check comments for more detail


Swift 4 :

Store

    UserDefaults.standard.set(object/value, forKey: "key_name")

Retrive

    var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]

Remove

    UserDefaults.standard.removeObject(forKey:"key_name")