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

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

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

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

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

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

Add Facebook "name" to PFUser ["fullname"] in swift

I have a registration/login method (from PFFacebookUtilsV4) that successfully adds a new PFUser object to my Parse database when a new Facebook user logs in. Within that method I make an FBSDKGraphRequest to get the basic user data (name, email). However I am having trouble adding the name and email to the newly created PFUser object. Here's my code so far:
#IBAction func facebookLogin(sender: AnyObject) {
PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile","email","user_friends"], block: { (user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name,email,picture.width(480).height(480)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
println("Error: \(error)")
ProgressHUD.showError("Error occurred.")
} else {
self.userFullName = result.valueForKey("name") as? String
println("User Name is: \(self.userFullName)")
self.userEmail = result.valueForKey("email") as? String
println("User Email is: \(self.userEmail)")
// Here I try to add the retrieved Facebook data to the PFUser object
user["fullname"] = self.userFullName
user.email = self.userEmail
self.performSegueWithIdentifier("login", sender: self)
println("User signed up and logged in through Facebook!")
ProgressHUD.showSuccess("Welcome \(self.userFullName)!")
}
})
} else {
println("User logged in through Facebook!")
ProgressHUD.showSuccess("Welcome \(self.userFullName)!")
self.performSegueWithIdentifier("login", sender: self)
}
} else {
println("User cancelled the Facebook login.")
}
})
}
Thanks! Any help is greatly appreciated.
Save the user after you add the new data inside the Facebook request closure.
user.saveEventually()
Or any other save that you prefer.