Firebase not storing logged in user - swift

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.

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.

Swift Firebase Login Registration auth

So when I first the page up I've kept it simple 2 text fields (email & password) 1 lbl 2 buttons (login register). Initially when I started out testing it everything worked when there was a problem an alert would pop up and tell you the problem, or you would be segue to next page based on button press and auth being complete.
But now every time I open the app to run code deeper inside no matter what I type I can sign in with the wrong password, or sign in with a previous email address even though previously these would both present errors. I have rebuilt this page numerous times over the week and decided to also add a get photo function from the users profile page.
Whenever I run the app and press a button I get this in the console:
Warning: Attempt to present on whose view is not in the window hierarchy!
I figure this is the problem because there is an error with the registration but the user is allowed to continue regardless. I've looked it up googled it read all the documentation I can find and even messed about trying and failing to put in a task structure.
PS I moved away from error label to use alerts hoping they would force a stop in the code
#IBAction func registerBtn(_ sender: Any) {
if emailTextField.text! == "" || passwordTextField.text == "" {
displayAlert(title: "Error", message: "Please Enter Your EMail Address & Choose A Password")
} else {
if let email = emailTextField.text {
if let password = passwordTextField.text {
//Create User
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
// Auth.auth().createUserAndRetrieveData(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
self.displayAlert(title: "Error", message: error!.localizedDescription)
} else {
print("Registration Successful")
self.performSegue(withIdentifier: "registrationSegue", sender: nil)
}
self.login()
})
}
}
}
}
if error != nil {
// show your alert
}
You don’t need an else statement on authenticating your users. so delete that line
Also, if you’re presenting a view controller that’s supposed to be accessible by authenticated users.
Please try:
let HomePage = HomePageController() // Change this to your viewcontroller name
self.present(HomePage, animated: true, completion: nil)
swift 4 - Xcode 9.1
func signUP(){
Auth.auth().createUser(withEmail: emailIdTextField.text!, password: passworTextField.text!) { (user, error) in
print(user?.email)
}
}
func signIn(){
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
print(user?.uid)
}
}
Swift 4.2
//creating user with email password authentication
Auth.auth().createUser(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
// completion handler
if error != nil {
print(error!)
} else {
//success
print("Registration Sucessful")
self.performSegue(withIdentifier: "goToChat", sender: self)
}
}

How do you connect to AWS Cognito in Swift for user signing up and logging in?

I'm going to start this question by apologizing for such an open ended question, but I am really struggling and all the documentation is outdated.
Amazon's provided sample app hasn't been updated and I get nothing but errors when attempting to run it. I have a login page setup and ready to go with email and password, and I have tried this code:
#IBAction func signInButtonTouched(sender: UIButton) {
if (emailTextField.text != nil) && (passwordTextField.text != nil) {
let user = (UIApplication.sharedApplication().delegate as! AppDelegate).userPool!.getUser(emailTextField.text!)
user.getSession(emailTextField.text!, password: passwordTextField.text!, validationData: nil, scopes: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: {
(task:AWSTask!) -> AnyObject! in
if task.error == nil {
// user is logged in - show logged in UI
} else {
// error
}
return nil
})
} else {
// email or password not set
}
}
but unfortunately I'm getting App Delegate has no member "userPool" errors. It does though! I am very new at this, and I have searched github and read through all of Amazon's samples, but the documentation is either in Objective-C, or outdated and doesn't work properly.
Any help with this would be vastly appreciated.

No FB access token upon initial Parse FB login

I am logging into my app using PFFacebookUtils.logInWithPermissions however, the first time I log in the actual login works fine but I get the FB error code = 2500 An active access token must be used to query information about the current user. This results in any graphRequests failing.
If I then recompile the code to the device this error does not occur and all graphRequests work fine. Why is the app not getting an access token upon the first login? Also, if I completely delete the app from the device and reinstall this whole process starts again (error code = 2500 on first attempt).
Also maybe worth noting, this didn't happen with the previous versions of Parse and FB SDKs. I am just starting to move this app into iOS9 and that's when this problem popped up.
Xcode 7.0.1, Parse SDK v1.8.5, FacebookSDKs-iOS-20150910
I was able to resolve this issue by first calling the FBSDK login method followed by the Parse SDK login method (inside the FBSDK callback):
#IBAction func facebookButtonAction(sender: AnyObject) {
// Ensure that PFUser == nil - just in here because I heard it can help with some possible issues
PFUser.logOut()
let permissions = ["public_profile", "email", "user_friends"]
// First, login with FB’s SDK
let login: FBSDKLoginManager = FBSDKLoginManager()
login.logInWithReadPermissions(permissions, handler: {(result: FBSDKLoginManagerLoginResult!, error: NSError!) in
if (error != nil) {
NSLog("Process error")
} else {
if result.isCancelled {
NSLog("Cancelled")
} else {
NSLog("Logged in")
// Then with Parse’s, upon FB login success
PFFacebookUtils.logInWithPermissions(permissions) { (user, error) -> Void in
if let user = user {
if user.isNew {
print("User signed up and logged in through Facebook!”)
//...
} else {
print("User logged in through Facebook!")
//...
}
} else {
print("Uh oh. The user cancelled the Facebook login.")
//...
}
}
}
}
})
}