Nick Nick - 6 months ago 63
Swift Question

Swift: How to store user preferences?

I am still very new to iOS development and swift and am not sure if I'm overthinking this. I am currently working on an application that upon opening requires the user to enter their login credentials. This gets tedious and frustrating because every time the app is closed and opened again the user has to sign in. Is there a simple way to make the program remember if a user is already signed in?

I was looking into CoreData but every example involves storing a new object every time and requires a query of some sort to fetch the information. Where as all I really need is a bool isLoggedIn and an int for the stored user ID.




Edit:

NSUserDefaults is exactly what I was looking for.

Answer

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")