Save Logged in state for appropriate user in IOS and Firebase - ios

I'm using only one login screen for different users on the app I'm developing and I added a code to save the logged in user so that the user doesn't have to log in again next time they open the app. But the fact that I have different users, I'm only able to send the user to one segue.
I've tried adding the code to keep the user logged in, but if I login with another user it sends the user to the same view controller as before. Here's what I tried:
override func viewDidAppear(_ animated: Bool) {
if Auth.auth().currentUser != nil {
// User is signed in.
performSegue(withIdentifier: "studentSegue", sender: self)
} else {
// No user is signed in.
return
}
}
I'm trying to keep the user logged in for different users, but I'm not sure what code to use. To differentiate the users on the login page I used switch case to find the user "Type" and log in on that. But I want to keep the appropriate user logged in. Any help would be much appreciated
EDIT: What am trying to say is if two people on different phones try to login lets say student (phone A) and teacher (phone B) they should just log in once and not have to log in again when they close the app. But my login "PerformSegue" only lets me show the "studentSegue"

Let me restate the question
On my app, I have two different types of users, student and teacher. When a student logs in or restarts the app, it should take them to the student section via a segue. When a teacher logs in or restarts the app, it should take them to a teacher section via a segue.
A few things
Firebase doesn't have user types, only users - to Firebase, every user is the same as every other user. Your app code and structure determine the difference.
One solution is to ask Firebase what kind of user it is upon app start. here's some generic code:
override func viewDidAppear(_ animated: Bool) {
if Auth.auth().currentUser != nil {
let uid = currentUser.uid
let thisUserRef = fbRoot.child("users").child(uid)
thisUserRef.observeSingleEvent(..... {
let userType = //get userType from snapshot
if userType == "student" {
performSegue(withIdentifier: "studentSegue", sender: self)
} else {
performSegue(withIdentifier: "teacherSegue", sender: self)
}
}
} else {
// No user is signed in.
return
}
}
Another option is to store the userType in the userDefaults. So if the user is auth'd, get the user type from the defaults and perform the appropriate segue. I am not a huge fan of this approach due to security but it can work.

After trying quite a lot i managed to find the answer myself. So what i did was set an integer with UserDefaults.standard.set(1, forKey: "isLoggedIn") each time a user would log in. I set number 1 for student and number 2 for teacher and in viewDidAppear i did this:
override func viewDidAppear(_ animated: Bool) {
if UserDefaults.standard.float(forKey: "isLoggedIn") == 1 {
self.performSegue(withIdentifier: "studentSegue", sender: self)
}
if UserDefaults.standard.float(forKey: "isLoggedIn") == 2 {
self.performSegue(withIdentifier: "lecturerSegue", sender: self)
}
else{
return
}
}

Related

UserDefaults Auto-Login isn't Working

So when the user first opens my app they will see a view with a button to proceed with logging in or registering. In my Login view, I have a button handler (attached via action) which is called when a user presses a login button. Despite me using UserDefaults to store logged in state, my app does not go straight to my Dashboard view automatically. Any ideas why?
// Firebase auth in doLogin action (Login VC)
Auth.auth().signIn(withEmail: un, password: pw)
{
(resp, err) in if (err == nil && resp != nil)
{
if (resp!.user.isEmailVerified)
{
// segue from Login VC to Dashboard VC will be exectuted
self.performSegue(withIdentifier: "loggedin", sender: nil)
// store the logged in state as true for the future
UserDefaults.standard.set(true, forKey: "loggedin")
UserDefaults.standard.synchronize()
}
}
}
Here is the code for the Main view controller to determine if it should proceed directly to dashboard.
func loggedIn() -> Bool {
// determine if the user is still logged into the app
return UserDefaults.standard.bool(forKey: "loggedin")
}
override func viewDidLoad() {
super.viewDidLoad()
if (loggedIn())
{
// logged in, return to the dashboard view controller
performSegue(withIdentifier: "persisted", sender: nil)
}
}
I've tried using print statements and either the loggedIn function isn't being executed for whatever reason or the console is just too flooded with Firebase debug log statements to even see these.
You have to embed your main view controller inside a UINavigationController to make the persisted segue work.

Segue Still Goes Through Despite Conditional Statement

I'm new to swift and Xcode. I creating a user registration view controller and I'm using Firebase as my DB. Here is what I've written:
#IBAction func registerButton(_ sender: Any) {
//Register user functions
Auth.auth().createUser(withEmail: emailField.text! , password: passwordField.text!) { (user, error) in
if error != nil {
print (error!)
} else {
//success
print ("Registration successful")
self.performSegue(withIdentifier: "registerToList", sender: self)
}
}
}
When a user inputs data that is incorrectly formatted, such as blank fields or improperly formatted email, my console prints out the error. However, the user is still able to bypass the registration view controller and move on to the next screen. Why is that?
I also want to note that I'm using a Show segue - is this the issue? I can't use a push segue since it has been deprecated.

Displaying a different view when user is logged in swift not working

I am developing an app in Swift3, and using Parse.
For my start screen, I have a Sign In page. However, I want it to automatically go to the Home screen if the user is Logged In.
override func viewDidLoad() {
super.viewDidLoad()
if PFUser.current() != nil {
print((PFUser.current()?.username)!)
self.performSegue(withIdentifier: "ShowHomePage", sender: self)
}
else {
print("No User Logged in")
}
That's my code on the SignIn page. Im getting the print message showing me that a user is Logged In, however, it's not actually going to a different view.
Any help would be much appreciated.

Update cached copy of Parse currentUser() in Swift

I have an ios application, I have implemented Facebook login through Parse. Everything works great in the first trial.
I can login via Facebook
My details are stored in the PFUser.currentUser()
I am able to pull information from the Graph API
But things start to become a problem when I logout (PFUser.logOut()) , and delete the User row from the Parse class and delete the app from Facebook.
The following methods still show that the user is logged in and authenticated.
if let user = PFUser.currentUser() {
if user.isAuthenticated()
I am guessing it is because current user is still using the cached copy of the User. I try executing
do
{
try PFUser.currentUser().fetch()
}
catch{
print("User refreshed")
}
But it does not refresh the currentUser() and gives an error. How can I refresh the PFUser.currentUser(), so that it stops saying that the user is logged in and authenticated, even though it's not
Thanks
I got an answer here,
Swift & Parse - PFUser currentUser never equals nil
I've been struggling with logging out for a little while and I believe I have finally cracked it!
No matter what I did, when I used "PFUser.logOut()" would never set "PFUser.currentUser()" to nil, but it would set "PFUser.currentUser()!.username" to nil...
Because of this I used
var currentUser = PFUser.currentUser()!.username
as a global variable to track is a user is logged in.
On my login/first page I added
override func viewDidAppear(animated: Bool) {
if currentUser != nil {
self.performSegueWithIdentifier("login", sender: self)
}
}
and finally on my logout button i used
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "logout" {
PFUser.logOut() //Log user out
currentUser = PFUser.currentUser()!.username //Reset currentUser variable to nil
}
}

Performing automatic segue using PFUser.currentUser() on app launch

I have an app that is using Parse to grab the locally stored currently logged in user for my app. When I launch the app from the home screen I want to avoid forcing my users to login everytime so I grab the currently logged in user using PFUser.currentuser() like this:
override func viewDidLoad() {
super.viewDidLoad()
println(PFUser.currentUser())
if PFUser.currentUser()?.username != nil {
self.performSegueWithIdentifier("LoggedIn", sender: self)
}
}
I then just want to perform a segue to a "dashboard" if that user has already logged in. the code
self.performSegueWithIdentifier("LoggedIn", sender: self)
works beautifully everywhere else in my code. However, when I try to use it in ViewDidLoad() is when it is giving me trouble. Can anyone help me with this?
The solution is to perform the code snippet in my question in the ViewDidAppear() func like this:
override func viewDidAppear(animated: Bool) {
println(PFUser.currentUser())
if PFUser.currentUser()?.username != nil {
self.performSegueWithIdentifier("LoggedIn", sender: self)
}
}

Resources