Creating new user with firebase in Swift - ios

I am new to Firebase and have been trying to implement a "Sign Up" page for my app. Currently, I am only using the email feature, just to test things out. I am able to create the new user and store it in the "Login & Auth" tab in the dashboard, but for what ever reason I cannot retrieve the UID. The only way is if I close out of my app and reload it, then it can access the UID. Any suggestions on why this is?

Swift 4.1 FireBase User Create/Login Steps:-
STEP 1:- Register new firebase authentication Pod in to your Podfile :
pod 'Firebase/Auth'
STEP 2:- Open terminal and install pod with your related project directory path:
pod install
STEP 3:- import firebase authentication library in your UIViewController where ever you want:
import FirebaseAuth
STEP 4:- On your Registration UIButton Action write this snippet :
Auth.auth().createUser(withEmail: (txtEmail.text ?? ""), password: (txtPass.text ?? "")) { (result, error) in
if let _eror = error {
//something bad happning
print(_eror.localizedDescription )
}else{
//user registered successfully
print(result)
}
}
STEP 5:- If you want to Sign In after Registration use this snippet on your Sign in UIButton:
Auth.auth().signIn(withEmail: (txtEmail.text ?? ""), password: (txtPass.text ?? "")) { (result, error) in
if let _eror = error{
print(_eror.localizedDescription)
}else{
if let _res = result{
print(_res)
}
}
}
Happy Codding ;)!!!!

Example of how to create users:
Auth.auth().createUser(withEmail: email, password: password, completion: { (result, error) -> Void in
if (error == nil) {
UserDefaults.standardUserDefaults().setValue(result.uid, forKey: "uid")
print("Account created :)")
let userDict = ["Name": name!, "Major": major!, "Email": email!]
let uid = result!.uid
self.dismissViewControllerAnimated(true, completion: nil)
}
else{
print(error)
}
})
Hope this helps.

Creating user in Firebase is very easy, just add firebase to your project using cocoa pods and then create a signup screen. You need email and password. Now first import Firebase
import Firebase
Then inside on viewDidLoad() method configure firebase
FIRApp.configure()
Now get email and password from textfields and use the following code for registration.
FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user: FIRUser?, error) in
if error == nil {
//registration successful
}else{
//registration failure
}
})
Thats it.
Source: Firebase Swift Tutorial

Before you try any code, make sure your password is at least 6 characters long. Print the error if is possible, I would print the error on each function. sign up and sign in just to keep track of what you are doing.
#IBAction func signUp(_ sender: Any) {
Auth.auth().createUser(withEmail: self.usernameTextField.text!, password: self.passwordTextField.text!) {(user, error) in
if user != nil {
print("User Has SignUp")
}
if error != nil {
print(":(",error)
}
}
Auth.auth().signIn(withEmail: self.usernameTextField.text!, password: self.passwordTextField.text!) {(user, error) in
if user != nil {
print("User Has Sign In")
}
if error != nil {
print(":(",error)
}
}

Related

Swift Firebase Auth Error

I'm currently working on an application with integrated Firebase login.
The last one I developed worked fine but the current App is causing a problem.
I'm taking the input from the Email and Password field and trying to login.
func login(user: String, pass: String){
Auth.auth().signIn(withEmail: user, password: pass) { (user, error) in
if(error != nil){
print("Success")
}
}
Every time I hit the "Login" button it prints "Success", even when I've not even entered Username and Password (blank text fields)
Code Snippet
Thanks for your Help in advance!
if (error != nil) ? Ok try to change if error == nil , because (error != nil) means that there is an error :).
func login(user: String, pass: String){
Auth.auth().signIn(withEmail: user, password: pass) { (user, error) in
if(error == nil){
print("Success")
} else {
print("error")
}
}

Firebase Email already in use error

I am trying to login to my user after updating firebase, and after tracing the error, I get the following error:
Error Domain=FIRAuthErrorDomain Code=17007 "The email address is
already in use by another account."
UserInfo={NSLocalizedDescription=The email address is already in use
by another account., error_name=ERROR_EMAIL_ALREADY_IN_USE}
After looking it seems to be a because that firebase user is already in use, I am not sure how to fix this. I believe it is because I never signed out the user before closing app, but not am unable to login as any of my users.
Below is my code:
#IBAction func Login(sender: AnyObject) {
let email = self._Email.text!
let password = self._Password.text!
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error == nil {
//successfull login
print("Successful login****************************************")
//performs a segue to the next view controller
if user!.isEmailVerified{
//if the email is verified
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ProfileView") as! ProfileView
self.present(vc, animated: true, completion: nil)
}
else {
print("email is not verified")
}
} else {
print("Some login error")
}
}
}
As ZassX pointed out, you're indeed using the signUp method of the Firebase iOS SDK, which is the createUserWithEmail. Use this method instead to signIn using email and password:
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
// ...
}
More info: https://firebase.google.com/docs/auth/ios/password-auth
You can check the list of your registered users in your Firebase Authentication Dashboard (https://console.firebase.google.com)
Also, it is good to print out the error description if you're having an error object. Like so:
print(error.localizedDescription).

Firebase Check if user already exists

I tried running the following and it does not work. What am I doing wrong to check the Firebase server if the user has already used the email?
FIRAuth.auth()!.createUser(withEmail: self.userEmailTextField.text!, password: self.userPasswordTextField.text!) {(createUser, error) in
if error != nil {
FIRAuth.auth()!.signIn(withEmail: self.userEmailTextField.text!, password: self.userPasswordTextField.text!)
//Display logged in
let viewController = self.storyboard!.instantiateViewController(withIdentifier: "TabBarController") as UIViewController
self.present(viewController, animated: true, completion: nil)
}else {
//Display an alert message
self.displayMyAlertMessage(userMessage: "Email already in use. Please see the login page.")
return
}
}
Please refer below code.
Code:
FIRAuth.auth()?.createUser(withEmail: email, password: password) {
(user, error) in
if (error) {
// Email is already in use.
} else {
// Create new user successfully
}
}
Handle Firebase iOS Auth Errors
Firebase already does this for you. Erase the sign in method and just run the create user method using an email that already exists and FIRAuthErrorCodeEmailAlreadyInUse will be returned. Check this out for more info

Invalid API Key supplied using Firebase

I'm using Firebase Auth to allow users to sign up using Facebook. I have taken all the steps from here to implement sign up including adding GoogleService-Info.plist to my project.
I get the Facebook permission screen all fine but when the app hits
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
this error is returned: An invalid API Key was supplied in the request.
Can anyone help me with this please?
Thanks
Here is my function code to log in using Facebook.
#IBAction func signUpWithFacebook() {
let fbLogin = FBSDKLoginManager()
fbLogin.logInWithReadPermissions(["email"], fromViewController:self, handler: {
(result, error) -> Void in
if ((error) != nil) {
print("Process error")
} else if (result.isCancelled) {
print("Cancelled");
} else {
print("Logged in");
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(accessToken)
print(FBSDKAccessToken.currentAccessToken().tokenString)
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
// ...
if let user = user{
print(user.displayName)
}
else{
if let error = error {
print(error.localizedDescription)
}
}
}
}
})
}
Solved it, for anyone that needs the solution in the future.
Sometimes API_KEY is missing from the GoogleService-Info.plist, this needs to be added.
The API Key can be found from Google API Console https://console.developers.google.com/
You can solve this by Downloading again the "GoogleService-Info.plist" file, under the Project Setting section on Firebase Console.
Ensure that the API_KEY is set on the new "GoogleService-Info.plist".

Swift Facebook login with Firebase sdk is not working correctly

I'm developing app which uses Firebase.
I tried to login with facebook with firebase sdk but I can't catch event when user finishes authentication with facebook.
With my code, Nothing is printed.
Event print("checking") is not working.
let ref = Firebase(url: "https://nos.firebaseio.com/users")
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self, handler: {
(facebookResult, facebookError) -> Void in
print("checking")
if facebookError != nil {
print("Facebook login failed. Error \(facebookError)")
} else if facebookResult.isCancelled {
print("Facebook login was cancelled.")
} else {
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
ref.authWithOAuthProvider("facebook", token: accessToken,
withCompletionBlock: { error, authData in
if error != nil {
print("Login failed. \(error)")
} else {
print("Logged in! \(authData)")
}
})
}
})
I'm using the latest version of xcode(7.2).
Is there anybody who has experience in this?
I'm looking for your answer.
I think there's a problem with your ref.
Try it without the /users
let ref = Firebase(url: "https://nos.firebaseio.com")
The rest of the login function works fine.

Resources