Login required for access
In order to watch this lesson, you'll need to login to the website.
UserDefaults to Save Logged In State
Audible Login Walkthrough
We'll be going over how to use UserDefaults to save data on the device today. Whenever a user logs in, we'll keep track of this information using a boolean and a key that we'll store inside of UserDefaults. Doing so will allow us a clean way to load our initial view based on the information we have about our user. As a bonus, let's go over a more robust way of saving things into UserDefaults by introducing an Enumeration for our string keys.
!codebreak <div class='filename'>LoginController.swift</div> !codebreak !syntax-highlight class LoginController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, LoginControllerDelegate { //... func finishLoggingIn() { //we'll perhaps implement the home controller a little later let rootViewController = UIApplication.shared.keyWindow?.rootViewController guard let mainNavigationController = rootViewController as? MainNavigationController else { return } mainNavigationController.viewControllers = [HomeController()] UserDefaults.standard.setIsLoggedIn(value: true) dismiss(animated: true, completion: nil) } //... } filebreak:MainNavigationController class MainNavigationController: UINavigationController { //... fileprivate func isLoggedIn() -> Bool { return UserDefaults.standard.isLoggedIn() } //... } !codebreak <div class='filename'>HomeController.swift</div> !codebreak !syntax-highlight class HomeController: UIViewController { override func viewDidLoad() { //... navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut)) //... } func handleSignOut() { UserDefaults.standard.setIsLoggedIn(value: false) let loginController = LoginController() present(loginController, animated: true, completion: nil) } } filebreak:UserDefaults+helpers extension UserDefaults { enum UserDefaultsKeys: String { case isLoggedIn } func setIsLoggedIn(value: Bool) { set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue) synchronize() } func isLoggedIn() -> Bool { return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue) } }

Comments (13)
5 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
HELP & SUPPORT