Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to store user preferences? [closed]

Tags:

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.

like image 442
Nick Avatar asked May 04 '15 23:05

Nick


People also ask

What should I store in user defaults?

You can use UserDefaults to store any basic data type for as long as the app is installed. You can write basic types such as Bool , Float , Double , Int , String , or URL , but you can also write more complex types such as arrays, dictionaries and Date – and even Data values.

Where are UserDefaults stored?

Storing Data in User Defaults The user's defaults database is stored on disk as a property list or plist. A property list or plist is an XML file. At runtime, the UserDefaults class keeps the contents of the property list in memory to improve performance.


2 Answers

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") 
like image 65
Ben Lu Avatar answered Sep 16 '22 18:09

Ben Lu


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  }  
like image 38
Exceptions Avatar answered Sep 20 '22 18:09

Exceptions