Pass data between ViewController and TableVC with NSUserDefaults (Swift) - ios

How to pass the state of a NSUserDefault between several Classes in Swift?
In this case I want to pass this state between one TableViewController, where you change the state on the switch, and one initial VC.
Here is a little model to understand...
I used this to set the state with the switch:
#IBAction func changeTouchIDState(sender: AnyObject) {
if TouchIDSwitch.on {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "State")
} else {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "State")
}
}
If the state = true, the initial VC should ask about the Authentication.
Thanks!

Your question need little more explanation, I don't understand why you want to pass the value as you are already storing in NSUserDefaults which you can access in any class of your app.
As per my understanding to your problem I'm suggesting the solution:
As you already storing State in NSUserDefaults so before presenting initial VC check NSUserDefaults.standardUserDefaults().boolForKey("State") if its true, ask authentication otherwise don't.

After setting the bool, you should synchronise:
NSUserDefaults.standardUserDefaults().synchronize()
Then, you can access that value with:
func boolForKey(_ defaultName: String) -> Bool

Related

Swift: How to check if UserDefaults exists and if not save a chosen standard value?

I am trying to check if a UserDefaults Key exists and if not set it to a standard value of my choice, but the answers here on stack overflow didn't help me to get this working.
Essentially I have a couple of UISwitches, one is on and the rest is set to off from the beginning. Now my problem is that I don't know how to save these initial states into UserDefaults when the viewController is loaded and those keys do not exists.
This is how I tried to check if the key for the UISwitch exists and if not set it to true (because that's the state I want it to be) and then check again what the bool for the key is and set the UISwitch to it (this is essentially important when the viewController is opened another time):
func setupSwitches() {
let defaults = UserDefaults.standard
//check if the key exists
if !defaults.bool(forKey: "parallax") {
switchParallax.setOn(true, animated: true)
}
//check for the key and set the UISwitch
if defaults.bool(forKey: "parallax") {
switchParallax.setOn(true, animated: true)
} else {
switchParallax.setOn(false, animated: true)
}
}
When the user presses the corresponding button I set the UserDefaults key like this:
#IBAction func switchParallax_tapped(_ sender: UISwitch) {
let defaults = UserDefaults.standard
if sender.isOn == true {
defaults.set(true, forKey: "parallax")
} else {
defaults.set(false, forKey: "parallax")
}
}
This is obviously working, but the problem is in the first code above.
First of all I am not sure how to check if it exists and if not set it to "true" and since the function is called setupSwitches() it is runs every time the viewController is shown.
So I don't know if there is a better way (eg. because of the memory issues) to check if a key exists, if not set it to true and if it already exists get the bool from UserDefaults and set the switch to the right state.
The problem is you can't determine exists with UserDefaults.standard.bool(forKey: key). UserDefaults.standard.object(forKey: key) returns Any? so you can use it to test for nil e.g.
extension UserDefaults {
static func exists(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
}

Accessing UserDefaults in Swift from other viewControllers

In my application, I use UserDefaults to store the user's login status (whether they are logged in or not), and their username. It works fine in that when I login, close the app, and open it again my app skips the login page and recognizes that I am already logged in. Although, I am now trying to install a logout button to a separate viewController. When clicked, this logout button needs to 1.) Reset UserDefaults.loginStatus to "False" 2.) Reset UserDefaults.username to nil 3.) Perform a segue to the login page.
Here is the related code from my ViewController.swift file. This is the first viewController which controls the loginPage.
import UIKit
import Firebase
let defaults = UserDefaults.standard
class ViewController: UIViewController {
func DoLogin(username: String, password: String) {
//I Am not including a lot of the other stuff that takes place in this function, only the part that involves the defaults global variable
defaults.setValue(username, forKey: "username")
defaults.setValue("true", forKey: "loginStatus")
defaults.synchronize()
self.performSegue(withIdentifier: "loginToMain", sender: self) //This takes them to the main page of the app
}
override func viewDidLoad() {
super.viewDidLoad()
if let stringOne = defaults.string(forKey: "loginStatus") {
if stringOne == "true" { //If the user is logged in, proceed to main screen
DispatchQueue.main.async
{
self.performSegue(withIdentifier: "loginToMain", sender: self)
}
}
}
}
Below is my code in SecondViewController.swift, particularly the logout function.
import UIKit
import Firebase
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let username = defaults.string(forKey: "username") {
checkAppSetup(username: username) //This is an unrelated function
//I included this because this works fine. Proving that I am able to read the defaults variable fine from this other viewController
}
}
#IBAction func logout(_ sender: Any) {
defaults.setValue("false", forKey: "username")
defaults.setValue("false", forKey: "loginStatus")
defaults.synchronize()
performSegue(withIdentifier: "logoutSegue", sender: nil)
}
When the logout function is run, the segue performs fine but the default values do not change. Can someone explain why and what I can do to get around this?
**Side note, I am not actually going to set the defaults to "false" and "false". That is just temporary for while I am debugging this issue.
Several things.
You should be using set(_:forKey:) and object(_:forKey) to read and write key/value pairs to defaults, not setValue(_:forKey). (Your use of defaults.string(forKey: "loginStatus") is correct, however.)
You should probably be writing a nil to the userName key:
defaults.set(nil, forKey: "username")
And your logout IBAction should almost certainly be setting loginStatus to false, not true.
Try changing those things.
Also, there is no reason to call synchronize unless you are terminating your app in Xcode rather than pressing the home button on the device/simulator in order to let it exit normally.
Hey i used the exactly same concept recently :
1) In your initial view, in the viewDidLoad() , check whether somebody is already logged in or not, and only one user can be logged in one device at a time, so we check like
let defaults = UserDefaults.standard
if defaults.object(forKey: "userName") != nil && defaults.object(forKey: "userPassword") != nil
{
let loginObject = self.storyboard?.instantiateViewController(withIdentifier: "YourSecondViewController") as! YourSecondViewController
//As someone's details are already saved so we auto-login and move to second view
}}
2) In your sign in button function , check whatever condition you want to check and then, inside the same, if condition satisfies then save data to userDefaults.
// If no details are saved in defaults, then control will come to this part, where we will save the entered userName and Password
let defaults = UserDefaults.standard
defaults.set(self.enteredUseName, forKey: "userName")
defaults.set(self.enteredPassword, forKey: "Password")
defaults.synchronize()
3) On logout button , delete the userDefaults and load the login view again :
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "userName") //We Will delete the userDefaults
defaults.removeObject(forKey: "userPassword")
defaults.synchronize() //Sync. the defaults.
navigationController?.popToRootViewController(animated: true) //Move Back to initial view.
4) If you are using a navigation control, that you must be using :P then you will surely see the back button which will open the second view if clicked, for that you can hide the navigation bar in viewDidLoad() of your login view
self.navigationController?.navigationBar.isHidden = true

How to save data in swift when changing view controllers?

So I have my main view controller and I have my settings view controller. When I go into the settings and flip a switch and go back to the main, my settings view controller goes back to its default settings and same with the name. How can I make it so it will save the data while the app is open and not go back to its default values?
Thanks
I prefer to use delegates instead of checking the user defaults every time I leave the settings page.
protocol SettingsViewControllerDelegate: class {
func settingsDidChange()
}
class SettingsViewController: UIViewController {
weak var delegate: SettingsViewControllerDelegate?
func someSettingChanged(){
let defaults = UserDefaults.standard
//... get the new settings
defaults.set(newSettingsValue, forKey: "settingsKey")
defaults.synchronize()
delegate?.settingsDidChange()
}
}
class MainViewController: UIViewController {
func showSettingsVC(){
let settingsViewController = //Initialization method
settingsViewController.delegate = self
self.show(settingsViewController, sender: self)
}
}
extension MainViewController: SettingsViewControllerDelegate{
func settingsDidChange() {
let defaults = UserDefaults.standard
if let settingsValue = defaults.value(forKey: "settingsKey"){
//// do the appropriate changes
}
}
}
you can store your button state in userdefault
here is the example for swift 3:
you can get button state in actioin for valuechanged then you can store that in
UserDefaults.standard.set(false, forKey: "buttonState")
let buttonState = UserDefaults.standard.bool(forKey: "buttonState")
if buttonState == true {
}
UserDefaults.standard.synchronize()
1) When view will appear call for setting screen get your data from NSUserDefaults and then fill data to options.
2) When user changes something update your UserDefaults and dont forget to Synchronize it.

uitextfield in swift 3 not saving

My textfield is not saving. My code is listed below. Thanks
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var textext: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func savesavesave(_ sender: Any) {
let myText = textext.text
UserDefaults.standard.set(myText, forKey: "myKey")
}
Ensure your textfield is not being first responder. For example, you may call the below code before saving:
#IBAction func savesavesave(_ sender: Any) {
textext.resignFirstResponder()
let myText = textext.text
UserDefaults.standard.set(myText, forKey: "myKey")
}
You should try this for saving textfield into UserDefaults:
let myText = TextFiled1.text
UserDefaults.standard.set(myText, forKey: "myKey")
If you want to get that textfield value then write this:
let value = UserDefaults.standard.string(forKey: "myKey")
print(value!)
Synchronize the user defaults with its method and test if working
I'm writing from my memory:
UserDefaults.standard.set(myText, forKey: "myKey")
UserDefaults.standard.synchronize()
EDIT
from apple documentation
// Note that we don't synchronize with the file system or anything; this will happen
when the app quits. There are times when an explicit synchronize might be necessary,
but often it's not. Synchronizing unecessarily can also be a performance issue.
According apple docs I understands (you may think otherwise) that if you want to get the value during runtime, and not saving it in your variable - you should sync manually
EDIT AGAIN
Thanks to #LeoDabus I understand that maybe it's available during runtime too. So don't count my answer
Yes, it is not necessary synchronize happens, if app is about to exit. For accessing the information during app launches it is necessary that the synchronization happens. For more info you can check: iOS NSUserDefaults access before synchronize completion

Best Way to Implement an Intro Sequence? Swift

I'm trying to add an intro sequence to my code so that if it's the first time the app is opened, the user can enter some basic information (which I can then store in UserDefaults).
The way that I was thinking of doing this is by having a variable called isFirstTime which is initially set to true. Every time the app is opened, it'll check if there is a value for isFirstTime in UserDefaults. If it isn't there, it'll trigger the View Controller that has my intro sequence to appear. Once the intro sequence is finished, isFirstTime will be set to false and then stored in UserDefaults.
Is this a correct implementation, or is there a more efficient way?
EDIT: If anyone is interested, this is the code I used to implement my intro sequence. I first assign a boolean variable outside of my View Controller that keeps track of whether it's the first time opening the app or not.
var isFirstTime = true
Then, in my ViewDidAppear (it does not work in the ViewDidLoad method), I added this code which checks whether or not I already have a UserDefault for my isFirstTime variable. If yes, I then execute the rest of my program, but if not, I start up my intro sequence's View Controller.
if UserDefaults.standard.object(forKey: "isFirstTime") != nil{
// Not the first time app is opened
isFirstTime = false // I use isFirstTime elsewhere in my code too.
} else {
let introVC = self.storyboard?.instantiateViewController(withIdentifier: "intro")
self.present(introVC!, animated: false, completion: nil)
}
In my intro sequence View Controller, when I am done with my gathering the user's basic information, I do two things: the first is changing the value of isFirstTime and setting it as a UserDefault, and the second is dismissing the View Controller.
isFirstTime = false
UserDefaults.standard.set(isFirstTime, forKey: "isFirstTime")
dismiss(animated: false, completion: nil)
You can achieve it easily. This is code which I have used for it.
Step 1 First create a file called UserDefaultManager.swift
import UIKit
// User Defaults Manager Constants
let kIsFirstTimeLaunch = "IsFirstTimeLaunch"
class UserDefaultsManager: NSObject {
// MARK: Setter Methods
class func setIsFirstTimeLaunch(flag: Bool) {
NSUserDefaults.standardUserDefaults().setBool(flag, forKey:kIsFirstTimeLaunch)
NSUserDefaults.standardUserDefaults().synchronize()
}
// MARK: Getter Methods
class func isFirstTimeLaunch() -> Bool {
return NSUserDefaults.standardUserDefaults().boolForKey(kIsFirstTimeLaunch)
}
// MARK: Reset Methods
class func resetIsFirstTimeLaunch() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(kIsFirstTimeLaunch)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
Step 2: In your Implementation file check it like below :
if(!UserDefaultsManager.isFirstTimeLaunch()) {
// Your code here.
let introVC = self.storyboard?.instantiateViewController(withIdentifier: "intro")
self.present(introVC!, animated: false, completion: nil)
// Update value in user defaults
UserDefaultsManager.setIsFirstTimeLaunch(true)
}

Resources