swift ERROR: Use of unresolved identifier 'authData' - swift

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

Related

an alert function that i created is calling several times for no reason

I am working on a project using firebase database and I save the users with their displayName instead of uid. I check if the displayName of the user who is trying to signup is on the list of displayNames on firebase and if not I allow user to signup with that displayName.
here is my signUp function;
func signUp(email: String, password: String) {
//gets the user data in the firebase
Database.database().reference().child("users").observe(.value) { [self] (snapshot) in
if snapshot.hasChild(self.userNameTxtField.text!){ //checking the displayName
self.present(alertFunction(message: "Seçmiş olduğunuz kullanıcı adı daha önceden alınmış."), animated: true)
} else {
Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
if let error = error as NSError? {...} else {
self.signIn(email: email, password: password)
}
}
}
}
}
and here is my signIn function;
func signIn(email: String, password: String) {
Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in
if let error = error as NSError? {...} else {
self.activityIndicator.stopAnimating()
self.view.isUserInteractionEnabled = true
//create database reference
self.ref = Database.database().reference()
//create new child and write a value on the existance child
if self.userNameTxtField.text == ""{
print("User Name can not be nill!")
self.present(self.alertFunction(message: "Kullanıcı adı boş bırakılamaz"), animated: true)
} else {
UserDefaults.standard.setValue(true, forKey: "userSignedIn")
if let currentUser = Auth.auth().currentUser?.createProfileChangeRequest() {
currentUser.displayName = self.userNameTxtField.text!
currentUser.commitChanges(completion: { error in
if let error = error {
print(error)
} else {
print("DisplayName changed")
self.ref.child("users").child(currentUser.displayName!).setValue(["nickname": self.userNameTxtField.text ?? ""])
self.ref.child("users/\(currentUser.displayName!)/step_count").setValue(Int(0))
self.ref.child("users/\(currentUser.displayName!)/total_point").setValue(Int(0))
self.ref.child("users/\(currentUser.displayName!)/onesignal_player_id").setValue("")
self.performSegue(withIdentifier: "showMainFromRegister", sender: self)
}
})
}
}
}
}
}
and finally here is my actionFunction;
func alertFunction(message: String) -> UIAlertController {
let alert = UIAlertController(title: "Uyarı!", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Tamam", style: .cancel, handler: nil))
self.activityIndicator.stopAnimating()
self.view.isUserInteractionEnabled = true
return alert
}
I call the signUp function after a button clicked and signUp func is calling the signIn function and if everything goes fine signIn function calls the performSegue function but after the performSegue
snapshot.hasChild(self.userNameTxtField.text!)
is triggered several time and the alert;
self.present(alertFunction(message: "Seçmiş olduğunuz kullanıcı adı daha önceden alınmış."), animated: true)
is displaying for no reason.
How can I solve the problem?
Replace
// listens for any change
.observe(.value) { [self] (snapshot) in
with
// listens for a change only once
.observeSingleEvent(of: .value, with: { [weak self] snapshot in

self.userUid = user.user.uid method still not working in 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

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

''Value of type 'AuthDataResult?' has no member 'uid'''

#IBAction func SignUpBtn_TouchUpInside(_ sender: Any) {
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { (user: AuthDataResult?, error:Error?) in
if error != nil{
print(error?.localizedDescription)
return
}
let ref = Database.database().reference()
let usersRenfence = ref.child("users")
let uid = user.uid
//(HERE IS WRONG, I DONT KNOW WHAT SHOULD I DO. It's my first time study code.)
let newUserRefernce = ref.child(uid)
newUserRefernce.setValue{["username": self.usernameTextField.text!, "email": self.emailTextField.text!]
print("description: \(newUserRefernce.description())")
Replace
let uid = user.uid
with
let uid = user!.user.uid
Look here in Docs

Save User's name in Firebase - Swift

I have three text field in my registration form. The e-mail id and password of the user are used by the Firebase SignUp method to create a new user. But I also want to save the user's name according to what they input.
My current code is;
#IBAction func registerPressed(_ sender: Any) {
SVProgressHUD.show(withStatus: "Setting you up")
dismissUIElements(value: false)
let currentUserName = userName.text
if currentUserName?.isEmpty == false {
FIRAuth.auth()?.createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { (user, error) in
if error != nil {
print(error!)
SVProgressHUD.dismiss()
self.dismissUIElements(value: true)
} else {
print("Registration Successful!")
SVProgressHUD.dismiss()
self.dismissUIElements(value: true)
self.performSegue(withIdentifier: "goToSelectionFromRegister", sender: self)
}
})
}
else {
SVProgressHUD.dismiss()
SVProgressHUD.showError(withStatus: "Please enter your name!")
SVProgressHUD.dismiss(withDelay: 1)
self.dismissUIElements(value: true)
}
}
You need a function that will register the user and then create the child for that user in Firebase.
let databaseRef=//your path to users.
func registerUser(userUsername userName:String, userEmail email:String, userPassword password: String, userCreationComplete: #escaping (_ status: Bool, _ error: Error?) -> ()) {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
guard let user = user else {
userCreationComplete(false, error)
return
}
let userData = ["userName": userName.text] as [String : Any]
ref.child(user.uid).updateChildValues(userData)
userCreationComplete(true, nil)
}
}
Then you call the function from within registerPressed() and you pass it the textfield values but make sure that none of them is empty.
You will create a new data table that stores that info. It won't be done in the create user function.
// create a reference to the DB
ref = Database.database().reference(fromURL: "https://your-project-name.firebaseio.com/")
//variables to store data
var myID : String?
var myName : String?
var myNumber : String?
var myEmail : String?
// creating the save user function
func saveUser(_ completion: #escaping(_ error: Error?) -> Void) {
if PageDataSource.sharedInstance.crudIsAvailable == true {
let usersRef = ref.child("users")
let myUserRef = usersRef.child(id)
myUserRef.updateChildValues(["User ID": id,
"Name": myName,
"Email": myEmail,
"Phone": .myNumber], withCompletionBlock: { (error, ref) in
if error != nil {
completion(error!)
} else {
completion(nil)
}
})
} else {
completion(NSError(domain: "Unavailable", code: 0, userInfo: nil))
}
}
// call the method like this to perform the save
func storeUser(completion: #escaping(_ completed: Bool, _ error: NSError?)-> Void) {
if let user = Auth.auth().currentUser {
myID = user.uid
myName = user.displayName
myEmail = user.email
// etc.,
completion(true,nil)
} else {
completion(false,NSError(domain: "No Current User", code: 1, userInfo: nil))
}
}