self.userUid = user.user.uid method still not working in Swift - swift

Ok so in my code I get this error:'Value of type 'AuthDataResult' has no member 'uid''. Even after trying to use the authDataResult or the self.userUid = user.user.uid, I'm still getting the error. Here's my code if anyone wants to help me
#IBAction func SignIn (_ sender: AnyObject) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
self.userUid = user.user.uid
KeychainWrapper.standard.set(self.userUid, forKey: "uid")
self.performSegue(withIdentifier: "toMessages", sender: nil)
} else {
self.performSegue(withIdentifier: "toSignUp", sender: nil)
}
})
}
}
Thanks if you can help me!

Inside if error == nil { do the following :
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
let email = user.email
}
You can find more information here:
https://firebase.google.com/docs/auth/ios/manage-users

Related

Does not add a user to Firebase

I am trying to add users to my Firebase cloud
I connected my project to the console.firebase
While I fill in the email and password it is not adding to my firebase.
I have the following code:
#IBAction func registerButton(_ sender: Any) {
signUp()
}
this is a button for register
and this is the func signup:
func signUp (){
let name = nameValue.text
let password = passwordValue.text
let email = emailValue.text
if (!password!.isEmpty && !email!.isEmpty) {
Auth.auth().createUser(withEmail: email ?? "", password: password ?? "") { (result, error) in
if error == nil {
if let result = result {
}
}
}
}
else {
showAlert()
}
}
Can anybody help to figure out this problem?
here is the solution to my problem:
if (!name!.isEmpty && !password!.isEmpty && !email!.isEmpty) {
Auth.auth().createUser(withEmail: email ?? "", password: password ?? "") { (authResult, error) in
if let e = error {
print(e.localizedDescription)
} else {
// self.performSegue(withIdentifier: "main", sender: self)
}
}
}

How do you know if a login problem is the result of a simulator or your code?

I have the issue that when a user logs in the homepage thereafter doesn't load properly, but when I stop the simulator and run it again (the the user is still logged in from the previous run) the page displays fine. I am wondering if this problem lies in the simulator or my code.
#IBAction func signInPressed(_ sender: Any) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "tohome", sender: nil) }
if error != nil{
print("Incorrect")
let alert = UIAlertController(title: "Error", message: "Incorrect Email or Password.", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
else {
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "tohome", sender: nil)
let databaseRef = Database.database().reference() databaseRef.child("people").child(userID).child("users").setValue(self.emailField.text!)
databaseRef.child("people").child(userID).child("postID").setValue(userID)
I would advice you to read the documents of signin in with email and password again.
There are lot of mistakes in the code. When you create the user it signs in automatically, you don't have to use the sign in method agin. Secondly you navigating to new screen before saving the data into database. When we have Users Defaults present why use KeychainWrapper?
First Create a model class so it will be easy for you to access the data and save data.
class User {
var userId: String?
var email : String?
var password: String?
// All the other information you want
init(dictionary:[String: AnyObject]){
userId = dictionary["userId"] as? String // "this will be your firebase node //make no typos here you can create a constant if you want"
email = dictionary["email"] as? String
password = dictionary["password"] as? String
// All the other database
}
}
now our model class is done it will be easy for us to save data
func createUserWithEmailAndPassword(){
if ( emailField.text != "" && passwordField.text != "" {
let email = emailField.text
let password = passwordField.text
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
// create error alert how you want.
return
}
let user = user?.user
let uid = user?.uid
let email = user?.email
let password = user?.password
// saving the user data locally
let userDefaults = UserDefaults
userDefaults.standard.set(uid, forKey: "user_uid")
userDefaults.standard.set(email, forKey: "user_email")
// etc etc
// after that we will be saving this user database to firebase database
// calling firebase save user function here which we will create below
self.registerUserToDatabase(uid: uid!, email: email!, password: password!)
}
}
func registerUserToDatabase(uid: String, email: String, password: String){
let userDb = Database.database().reference.child("people").child("users").child(uid)
// Make sure the key value in the below dictionary matches the User model class you var you made
let userDictionary = ["userId": uid, "email": email,"password": password] as [String: AnyObject]
userDb.updateChildValues(userDictionary) {(err ,userDb) in
if err != nil {
// alert view for error
}
let users = User(dictionary: userDictionary)
// Below we will navigate to to home screen or which ever screen you want
self.navigateToApp()
}
}
create a navigate to controller function
func navigateToApp(){
// performe seque method
}
// PS what is wrong with GitHub formatter

swift ERROR: Use of unresolved identifier 'authData'

I do not know why its saying that 'uid' has no member.
Type 'User' has no member 'user'
My code:
#IBAction func signIn (_ sender: AnyObject) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().signIn(withEmail: email, password: password, completion: { (authDataResult: AuthDataResult?, error) in
if error == nil {
self.userUid = authDataResult?.user.uid
KeychainWrapper.standard.set((User.user.uid)!, forKey: "uid")
self.performSegue(withIdentifier: "toMessages", sender: nil)
} else {
self.performSegue(withIdentifier: "toSignUp", sender: nil)
}
})
}
}
You are making a class reference, that is you expect the class User to have a static property user which it doesn't
KeychainWrapper.standard.set((User.user.uid)!, forKey: "uid")
Maybe you meant the uid you just read
KeychainWrapper.standard.set(self.userUid!, forKey: "uid")

Cannot assign to value: 'user' is a 'let' constant - FIXED

I am trying to create a login page where user logs in with Auth Email/Password and if they are declared admin or user the performSegue takes to a different page.
Here is my code:
#IBAction func submit(_ sender: UIButton) {
if let email = txtemail.text, let passowrd = txtpass.text {
Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
Database.database().reference().child("user").child("admin")
if user = true {
self.performSegue(withIdentifier: "adminlogin", sender : self)
}
if user = false {
self.performSegue(withIdentifier: "login", sender : self)
}
}
}
However keeps coming up with this error:
Cannot assign to value: 'user' is a 'let' constant
ANSWERED:
I fixed this by doing this to my code:
{ Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
if user != nil {
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("user").child(uid!).child("admin").observeSingleEvent(of: .value, with: { (snapshot) in
// Checking if user is found
if snapshot.exists() {
// admin is found
self.performSegue(withIdentifier: "adminlogin", sender : self)
} else {
// admin is not found going to user login
self.performSegue(withIdentifier: "login", sender : self)
}
})
Now when I log in with Admin I go to another View Controller, than if I log in with a User.
= is used as an assignment operator
== is the comparison operator
You want to use == to make the comparison.
The user and error objects are immutable, meaning you can't change them. But they are holding values that you want to check.
I've updated your code to work:
#IBAction func submit(_ sender: UIButton) {
if let email = txtemail.text, let passowrd = txtpass.text
{
Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
Database.database().reference().child("user").child("admin")
if user == true {
self.performSegue(withIdentifier: "adminlogin", sender : self)
}
if user == false {
self.performSegue(withIdentifier: "login", sender : self)
}
}
}
}
You have put if user = true A single = is an assignment. To check a value is equal to something use if user == true
You can't check if the user is an admin or not by comparing it to true or false. I suggest to log the user in and after that validating if the UID is an admin by so:
let databaseRef = Database.database().reference(withPath: "user/admin/(UID after logged in)")
databaseRef.observeSingleEvent(of: .value, with: { (snapshot) in
// Checking if user is found
if snapshot.exists() {
// admin is found
self.performSegue(withIdentifier: "adminlogin", sender : self)
} else {
// admin is not found going to user login
self.performSegue(withIdentifier: "login", sender : self)
}
})

Swift: Using credentials with Firebase and a additional textfield for username

I have a few things I'm trying to accomplish. First, my email and password don't matter if they're filled or not to login. I would like the app to check if email and password is filled and correct before logging in. Secondly, I would like to put in a username when they register so it would show up on the profile page and tell other users who they're without revealing an email address. I'm using Firebase and I thought this would do the trick, but it doesn't. I looked over this Stack overFlow Post and have everything correct I think, but its still letting you login without credentials.
#IBAction func loginRegisterBtnPressed(_ sender: AnyObject) {
performSegue(withIdentifier: "profileVC", sender: self)
if let email = emailTextField.text, let password = passwordTextField.text {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error ) in
if error == nil {
print("DAW: User Created")
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error ) in
if error != nil {
print ("DAW: User failed to authenticate with Firebase")
} else {
print ("DAW: Successfully")
if let user = user {
self.completeSignIn(id: user.uid)
}
}
})
}
})
}
}
#IBAction func loginRegisterBtnPressed(_ sender: AnyObject) {
if let email = emailTextField.text, let password = passwordTextField.text {
if email != "" && password != ""{
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error ) in
if error == nil {
performSegue(withIdentifier: "profileVC", sender: self)
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error ) in
if error != nil {
print ("DAW: User failed to authenticate with Firebase")
} else {
print ("DAW: Successfully")
if let user = user {
self.completeSignIn(id: user.uid)
}
}
})
}
})
}
}
}