Segue not being called - swift

I am trying to bypass a sign-in view if the user has already signed in once. I have run tests and know I'm getting to the right code. But the segue is never executed.
//bypass the sign in screen if user has already signed in
let signInCheck = NSUserDefaults.standardUserDefaults().valueForKey("editProfile")
if (signInCheck! .isEqual(1)) {
self.performSegueWithIdentifier("loggedIn2", sender: nil)
} else {
NSUserDefaults.standardUserDefaults().setValue(1, forKey: "editProfile")
}
Any help would e appreciated.

Related

Checking Sign-in Status for Each ViewController

I am a beginner. I am developing an app with swift. I am using Firebase for signin. But I was wondering if I need to write codes to check user's sign-in status for each viewController for security. Or sign-in is needed only for the sign-in viewController like locking just a front door. My code may not be needed but below is the code that I wrote:
// Mark: User Sign-in Status Recheck
Auth.auth().addStateDidChangeListener { auth, user in
if user != nil {
if let user = user {
let userUid = user.uid
let userEmail = user.email
}
} else {
let InitialSignInFirstViewController = self.storyboard?.instantiateViewController(withIdentifier: "SignInFirstViewController") as! InitialSignInViewController
self.present(SignInFirstViewController, animated: false, completion: nil)
}
}
In my app I have a swift page that checks if the user is signed in when the app loads. If they are signed in they continue to the app, and you don't need to check until the app quits, and opens again. If they aren't signed in they go to another view controller to get signed in.
You don't need to manage the state or run the listener, there is more simpler way to do that, i.e.,
if Auth.auth().currentUser != nil {
// User is signed in.
// ...
} else {
// No user is signed in.
// ...
}
Update
You can create one class which just provide the user sign in status like below:
struct UserSignInStatus {
var isLoggedIn: Bool {
return (Auth.auth().currentUser != nil)
}
}
Usage: UserSignInStatus.isLoggedIn
You can put this code any where like in your AppDelegate class where you check the signin status and depending on that managing your rootViewController. Let me know if you need any more help.

Is there a way to perform a conditional segue in a swift ViewController?

I am attempting to authenticate user sign in using Firebase. If a user's credentials are verified, I am seguing to the home screen of my application within an if-else statement using user and error. However, performSegue(...) executes whether or not the log in actually occurred.
I am certain that the problem is not with verification/login/logout issues in Firebase or with the textfields.
Here is my code:
func handleSignIn(username:String, password:String) {
Auth.auth().signIn(withEmail: username, password: password) { user, error in
if error == nil && user != nil {
//self.dismiss(animated: false, completion: nil)
print("Logged in!")
self.performSegue(withIdentifier: "toHome", sender: nil)
} else {
print("Error logging in: \(error!.localizedDescription)")
}
}
}
Best,
Code Daddy
I have solved this issue.
The code above is actually correct and functional. The issue was that the handleSignIn method was called within:
#IBAction func didTapLogin(_ sender: Any) {...}
That button itself was the segue connection with the identifier "toHome," and so regardless of what the if/else block evaluated to, the application proceeded to the home menu.
Once I deleted and reestablished the segue "toHome" from the LoginViewController to the HomeViewController (not the Log In button to the HomeViewController), this code worked properly.

Firebase not storing logged in user

Was working with Firebase for almost half year now and never had this issue. Using code just like before to create new user, he shows up in console, when i close app i can sign in but using same code as always it keeps prompting me for password. In first VC i have:
if let user = Auth.auth().currentUser {
performSegue(withIdentifier: "authorized", sender: self)
}
Which will check if there is auth token stored and perform segue to loading screen. However this never happens. The code is ran but doesn't do anything, no errors in compiler and no errors in console.
EDIT 1: also tried to create new project where i rewrote all the code getting same result, but my other project works without any issues, also i'm able to do anything else besides this using firebase such as access Firestore just not storing the user, went over all the documentation but couldn't find any solution.
EDIT 2: sign in code
if(email.text != "" && password.text != ""){
Auth.auth().signIn(withEmail: email.text!, password: password.text!) { user, error in
if(error == nil && user != nil) {
userID = (Auth.auth().currentUser?.uid)!
print("Signed in as: \(userID)")
self.performSegue(withIdentifier: "load", sender: self)
} else {
print("Error found: \(error?.localizedDescription)")
}
}
}
Solution:
DispatchQueue.main.async(){
if let user = Auth.auth().currentUser {
userID = (Auth.auth().currentUser?.uid)!
self.performSegue(withIdentifier: "authorized", sender: self)
}
}
Loaded with async so firebase will configure before checking for auth
The issue is likely that you are calling your code before firebase has properly initialized. I recommend using the entry view controller's viewDidAppear for things such as these. If you were using viewDidLoad, it is likely that firebase did not load yet.

Swift programmatically set segues

I have a piece of parse code that checks to see if a user is logged in:
PFUser.logInWithUsernameInBackground("myname", password:"mypass") {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
// Do stuff after successful login.
} else {
// The login failed. Check error to see why.
}
}
After the successful login I want to send the user to a new segue. I can't do this in the storyboard because I only want the segue to occur if the conditions are met. Is there anyway to create a segue programmatically?
You can use:
performSegueWithIdentifier("yourSegueIdentifier", sender: nil)
You dont need to "create" a segue programmatically, just connect your ViewControllers and create a Segue. With performSegueWithIdentifier you can call your segue manually if needed.

PerformSegue in StoryBoard

I am working for the first time on storyboard using Swift.
In the first page of the app user will login and when login is done successfully, user will navigate to next page.
But When button is clicked firstly navigation occurs then after web service gets called, but what I want is to authenticate the Login Web service first then navigate with login data to next page.
I have put the identifier on the login button i.e, "login_success" on the button in storyboard and called self.performSegueWithIdentifier, when login is successfull.
Please guide me. Thanks.
You can add segue in the identifier in storyboard. Set the segue in the storyboard from File Owner. And when we get the response from the server, then using,
dispatch_async(dispatch_get_main_queue(), {
if self.loginInfo.userEmail.length > 0{
self.performSegueWithIdentifier("login_success", sender: self)
}
})
Here, I am checking whether response string has value or not.
Then call the method of segue to navigate to next page.
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
{
if segue.identifier == "login_success"
{
var mainVC: MainViewController!
mainVC = segue.destinationViewController as MainViewController
mainVC.mainLoginInfo = loginInfo
}
}
MainViewController is the page to which I want to move after login is done successfully.