Swift: How to store user preferences?

You can use NSUserDefaults to save information and retrieve it next time when the app launches.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html

For example:

NSUserDefaults.standardUserDefaults().setObject("mynameisben", forKey: "username")

let userName = NSUserDefaults.standardUserDefaults().stringForKey("username")

Update for Swift 3+

UserDefaults.standard.set("mynameisben", forKey: "username")

let userName = UserDefaults.standard.string(forKey: "username")

Use NSUserDefaults

Let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("User", forKey: "userName")

Check if User name exists when application is started in your AppDelegate.swift

didFinishLaunchingWithOptions

If username exists, skip login page

To check if NSUserDefaults is nil

if (defaults.objectForKey(userName) != nil) { 
// Skip Login 
}
else {// Show login 
} 

Tags:

Ios

Swift