Firebase Authentication using Email & Password - iOS, Swift - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

26 Sept 2017

Firebase Authentication using Email & Password - iOS, Swift

Now a days most of mobile developers are using Firebase in their projects.

For getting the data from Firebase we need to get authorization from Firebase. This can be done by Sign Up/Log In into Firebase.

Firebase Authentication using Email & Password

There are different Sign Up/Log In providers.

In this article we will go through Sign Up/Log In using Email & Password.

Before getting into Firebase Authentication, First we need to setup Firebase to our project.

If not, read setting up Firebase.

Next step is add the following pod file to our project.
pod 'Firebase/Auth'

Then, run pod install and open the created .xcworkspace file.

Initialize the Firebase SDK :

We need to initialize Firebase for Authentication.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Next go to Firebase console -> Authentication -> Sign-in Method there enable required logins.Here we enable Email/Password sign In provider.

 Firebase console -> Authentication -> Sign-in Method


Sign Up:

We need to collect user email and password for Firebase Authentication.

For creating new user, use the following method:
Auth.auth().createUser(withEmail: "test@email.com", password: "password") { (user, error) in
    if let error = error {
        print(error.localizedDescription)
        return
    }
    
    print("\(user!.email!) created")
}

After successful sign up we are printing user email from user object.

Sign In:

For signing in with email and password use the following code:
Auth.auth().signIn(withEmail: "test@email.com", password: "password") { (user, error) in
    if let error = error {
        print(error.localizedDescription)
        return
    }
    
    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
        let photoURL = user.photoURL
        // ...
    }
}

After a user signs in successfully, you can get information about the user.

Sign Out:

In order to sign out from Firebase write the following code:
let firebaseAuth = Auth.auth()
do {
    try firebaseAuth.signOut()
} catch let signOutError as NSError {
    print ("Error signing out: %@", signOutError)
}

It will sign Out from Firebase and we can't access to Firebase.

Next Steps:

Authenticate with Firebase using Facebook Login

 

Authenticate with Firebase Anonymously on iOS

No comments:

Post a Comment

Post Top Ad