Swift Firebase Login Registration auth - swift

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

Related

How to check if email already exist before creating an account (Swift)

I know different variations of this question have been asked. However I seem to keep running into the same issue every time.
I want to check if an email already exist before the user pushes onto the next view. I will enter an email that exist in the database and the performSegue func is always called and pushes the user as if that email does not exist.
The only way I can check officially is when the user reaches the final sign up VC and the Auth.auth().createUser(withEmail: email as! String, password: password as! String ) { (user, error) in code will check for all errors.
However for good user experience I would hate for the user to have to click back three times to change the email address. Here is the code I have for the enter email view controller.
// Check if email is already taken
Auth.auth().fetchSignInMethods(forEmail: emailTextField.text!, completion: { (forEmail, error) in
// stop activity indicator
self.nextButton.setTitle("Continue", for: .normal)
self.activityIndicator.stopAnimating()
if let error = error {
print("Email Error: \(error.localizedDescription)")
print(error._code)
self.handleError(error)
return
} else {
print("Email is good")
self.performSegue(withIdentifier: "goToCreateUsernameVC", sender: self)
}
})
First off am I even entering the create property in the forEmail section? I added emailTextField.text because its the only way I know how even get the email the user typed. Does anyone know a better way I can do this?
How I create user accounts
This is an example of what I use. When a user provides credentials, FirebaseAuth checks if these credentials can be used to make a user account. The function returns two values, a boolean indicating whether the creation was successful, and an optional error, which is returned when the creation is unsuccessful. If the boolean returns true, we simply push to the next view controller. Otherwise, we present the error.
func createUserAcct(completion: #escaping (Bool, Error?) -> Void) {
//Try to create an account with the given credentials
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordConfirmTextField.text!) { (user, error) in
if error == nil {
//If the account is created without an error, then we will make a ProfileChangeRequest, i.e. update the user's photo and display name.
if let firebaseUser = Auth.auth().currentUser {
let changeRequest = firebaseUser.createProfileChangeRequest()
//If you have a URL for FirebaseStorage where the user has uploaded a profile picture, you'll pass the url here
changeRequest.photoURL = URL(string: "nil")
changeRequest.displayName = self.nameTextField.text!
changeRequest.commitChanges { error in
if let error = error {
// An error happened.
completion(false, error)
} else {
//If the change is committed successfully, then I create an object from the credentials. I store this object both on the FirebaseDatabase (so it is accessible by other users) and in my user defaults (so that the user doesn't have to remotely grab their own info
//Create the object
let userData = ["email" : self.emailTextField.text!,"name": self.nameTextField.text!] as [String : Any]
//Store the object in FirebaseDatabase
Database.database().reference().child("Users").child(firebaseUser.uid).updateChildvalues(userData)
//Store the object as data in my user defaults
let data = NSKeyedArchiver.archivedData(withRootObject: userData)
UserDefaults.standard.set(data, forKey: "UserData")
UserDefaults.standard.set([Data](), forKey: "UserPhotos")
completion(true, nil)
}
}
}
} else {
// An error happened.
completion(false, error)
}
}
}
Here is an example of how I would use it. We can use the success boolean returned to determine if we should push to the next view controller, or present an error alert to the user.
createUserAcct { success, error in
//Handle the success
if success {
//Instantiate nextViewController
let storyboard = UIStoryboard(name: "Main", bundle: .main)
let nextVC = storyboard.instantiateViewController(withIdentifier: "NextVC") as! NextViewController
//Push typeSelectVC
self.navigationController!.pushViewController(viewController: nextVC, animated: true, completion: {
//We are no longer doing asynchronous work, so we hide our activity indicator
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
})
} else {
//We now handle the error
//We are no longer doing asynchronous work, so we hide our activity indicator
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
//Create a UIAlertController with the error received as the message (ex. "A user with this email already exists.")
let alertController = UIAlertController(title: "Error", message: error!.localizedDescription, style: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, action: nil)
//Present the UIAlertController
alertController.addAction(ok)
self.present(alertController, animated: true, completion: nil)
}
}
Let me know if this all makes sense, I know there is a lot to it. I'm just considering things you'll maybe find you need done anyways that you may not be aware of (like making change requests, or storing a data object on FirebaseDatabase).
Now for checking if the email is already taken:
Remember when I said that I post a user object to FirebaseDatabase upon account creation? Well we can query for the given email to see if it already exists. If it doesn't we continue with the flow as normal, without having actually created the account. Otherwise, we simply tell the user to pick another email address.
Pushing a user object to your database (taken from the above code):
if let firebaseUser = Auth.auth().currentUser {
//Create the object
let userData = ["email" : self.emailTextField.text!,"name": self.nameTextField.text!] as [String : Any]
//Store the object in FirebaseDatabase
Database.database().reference().child("Users").child(firebaseUser.uid).updateChildvalues(userData)
}
And now querying to see if somebody already has that email:
func checkIfEmailExists(email: String, completion: #escaping (Bool) -> Void ) {
Database.database().reference().child("Users").queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .value, with: {(snapshot: DataSnapshot) in
if let result = snapshot.value as? [String:[String:Any]] {
completion(true)
} else {
completion(false)
}
}
}
Then we can call this like so:
checkIfEmailExists(email: emailTextField.text!, completion: {(exists) in
if exists {
//Present error that the email is already used
} else {
//Segue to next view controller
}
})

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.

Integrating Facebook Login with Parse Swift 3

In my Xcode Project I already have a sign in feature that uses a user's username and password they created. Now I want to integrate a Facebook login in the project, but I am not completely sure how to do this. When someone makes an account through they way I have it now, they make and save a username and a password which can then be used in with PFUser.logIn(withUsername: ..., password: ...) for whenever they want to sign in again.
But with Facebook, I do not know what unique identifier I am suppose to save their account with. I know there is a Facebook id that I can extract, but how do I login the user in after I get this? Like I said before I currently use PFUser.logIn(withUsername: ..., password: ...) to log the users' in then I just use PFUser.current()?.username to get all data related to that user. I heard that I am suppose to use PFFacebookUtils.logInInBackground for this, but I already tried implementing it but when I press the "Continue with Facebook button", the app crashes (I screenshot error and placed it at bottom). I have copied my code of what I have so far. How do I integrate a signup with Facebook feature that will allow me to save a users Facebook id and what method do I use to sign the user in (i.e. PFFacebookUtils.logInInBackground)? Here's my code so far:
#IBOutlet var facebookSignUpButton: FBSDKLoginButton!
var fullnameFB = String()
var idFB = String()
var emailFB = String()
var isFBSignUp = Bool()
override func viewDidLoad() {
super.viewDidLoad()
signUpWithFacebook()
}
func signUpWithFacebook() {
facebookSignUpButton.readPermissions = ["email", "public_profile"]
facebookSignUpButton.delegate = self
self.view.addSubview(facebookSignUpButton)
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil { //if theres an error
print(error)
} else if result.isCancelled { // if user cancels the sign up request
print("user cancelled login")
} else {
PFFacebookUtils.logInInBackground(with: result!.token!) { (user, error) in
if error == nil {
if let user = user {
if user.isNew {
print("User signed up and logged in through Facebook!")
} else {
print("User logged in through Facebook!")
}
if result.grantedPermissions.contains("email") {
if let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email, name"]) {
graphRequest.start(completionHandler: { (connection, result, error) in
if error != nil {
print(error?.localizedDescription ?? String())
} else {
if let userDetails = result as? [String: String]{
print(userDetails)
self.fullnameFB = userDetails["name"]!
self.idFB = userDetails["id"]!
self.emailFB = userDetails["email"]!
self.isFBSignUp = true
}
}
})
}
} else {
print("didnt get email")
self.createAlert(title: "Facebook Sign Up", message: "To signup with Facebook, we need your email address")
}
} else {
print("Error while trying to login using Facebook: \(error?.localizedDescription ?? "---")")
}
} else {
print(error?.localizedDescription ?? String())
}
}
}
}
Console output:
2017-08-12 14:14:33.223472-0700 Project[2423:1001235] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'You must initialize PFFacebookUtils with a call to +initializeFacebookWithApplicationLaunchOptions'
*** First throw call stack:
(0x188042fe0 0x186aa4538 0x188042f28 0x100b8f934 0x100b90020 0x100b9032c 0x10019eee8 0x1001a0a64 0x100867598 0x10086e998 0x10086e4f0 0x100871a94 0x18b3610d4 0x101521a10 0x101526b78 0x187ff10c8 0x187feece4 0x187f1eda4 0x189989074 0x18e1dd364 0x1001ec288 0x186f2d59c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
As stated in the docs, you need to initialize PFFacebookUtils before using it, like so:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// CODE...
PFFacebookUtils.initializeFacebook(applicationLaunchOptions: launchOptions)
}
Important: Must be done after Parse setup (Parse.initialize...).

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.