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.
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.
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.
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")
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With