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

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)
}
}

Related

Save Logged in state for appropriate user in IOS and Firebase

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
}
}

Persisting data in iOS app

I am new to iOS. I want to save authentication token recieved from a REST API to use in further api calls without requiring a login. Currently I am using UserDefaults to store this token. This token works fine unless app is completely closed. Relaunching the app again takes me to login screen.
Saving the token like this
UserDefaults.standard.setValue(authToken, forKey: "auth_token")
UserDefaults.standard.synchronize() // Now this call is derpecated. Framework handles this call at proper places.
LoginViewController
override func viewDidLoad(){
super.viewDidLoad()
if UserDefaults.standard.string(forKey: "auth_token") != nil {
self.performSegue(withIdentifier: "login_success", sender: self)
}
}
But the issue is how can I persist this token even after the app was completely closed ?
EDIT
I have also tried syncing UserDefaults within applicationWillTerminate methods of AppDelegate class just to make sure but that even doesn't work.
Nothing wrong with the UserDefaults. Just wrapping the triggering segue call in main queue was required to properly work.
override func viewDidLoad() {
super.viewDidLoad()
if UserDefaults.standard.string(forKey: "auth_token") != nil {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "login_success", sender: self)
}
}
}

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.

Parse User Auto Login

I'm trying to get my app to segue directly to the Profile Page after start is a PFUser is already logged in that way they won't have to keep logging in unless the completely stop the app. It's not working. Maybe I'm not checking for PFUser nil correctly. Please help. Here's what I'm putting in viewDidLoad.....
override func viewDidLoad()
{
super.viewDidLoad()
if PFUser.currentUser()?.username != nil
{
self.performSegueWithIdentifier("loginToProfileSegue", sender: self)
}
Please help.

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
}
}

Resources