From this Firebase iOS Tutorial we will start using Firebase for our iOS Application. I am starting this Firebase iOS Tutorial series to help you all in integrating Firebase in your iOS Application. This is the first post in Firebase iOS Tutorial series and today we will see an example of Firebase Authentication. I will be using Swift. So lets start our Firebase iOS Tutorial.
Contents
What is Firebase?
The very obvious question if you don’t know what is firebase. Firebase is a cloud service provider. It is now under google. And with Firebase you can replace your application backends.
If you remember the last Swift PHP MySQL Tutorial, then you know that for storing data in a centralized server we need to code the REST APIs for communicating with the database. But if we use Firebase we do not need to worry about server side codes and REST APIs. Firebase will do everything for us that is needed for our application backends.
Firebase provides number of features that are very important in mobile application development. In the below image you can see the services provided by Firebase.
With this series I will be covering all features or firebase. We are starting with Firebase Authentication.
Making the System Ready
To start using firebase first we will install CocoaPods in our system. Now if you don’t know what is CocoaPods then it is a tool for managing your iOS App’s Dependencies. It is needed to add firebase in our application. So lets install CocoaPods first.
Installing CocoaPods
- Open terminal and run the following commands. It may take some time depending on your internet speed.
$ sudo gem install cocoapods --pre
- Now we have done with CocoaPods installation. The next thing we need is a Firebase Application in Firebase Console.
Creating a Firebase App
Now we will create a firebase application in firebase console. So start following the below given steps.
- Go to firebase.google.com and then click on Get Started For Free.
- Now you will be navigated to Firebase Console, here you will see all the previous projects created. And from here you can create new projects as well. So click on Create New Project.
- You will see a new form asking your project name. Just enter your project name (I am giving SimplifiediOS) and then click on Create Project.
- Now you will be redirected to the Firebase Console for the app you just created as you can see in the following screenshot.
- Thats it you have successfully created your Firebase Application. Now you can use all the firebase features. Minimize the firebase console for now and lets start our Xcode Project.
Creating Xcode Project
- Open Xcode and create a new project.
- Select a SingleView Application and click on Next.
- Now put your application details and create your project.
- You will see the following screen once your project is loaded.
- Copy this Bundle Identifier, it is needed for adding this app in Firebase Console.
Adding App to Firebase Project
- Now we will add our Xcode Project to Firebase Project. So again go to Firebase Console and Add Firebase to iOS App.
- Now in the Form you are seeing paste the Bundle Identifier you copied and click on Add App.
- After clicking on Add App you will get a file named GoogleService-Info.plist. We need to add this file in our Xcode Project.
- Now you can skip to Firebase Console.
Enabling Firebase Auth
- As in this post we will be covering User Registration with Firebase Auth. So click on Auth from the left side menu in Firebase Console.
- Now click on Set Up Sign-In Method.
- Now Enable Email/Password and Save.
- Now we have enabled the Firebase Auth. We can now use Firebase Auth in your application.
Firebase User Registration
Adding GoogleService-Info.plist
- Come to Xcode Project and secondary click on your project directory.
- Now select the GoogleService-Info.plist file that we already downloaded and click on add.
- Now close Xcode.
Adding Firebase Auth Dependency
- Open Terminal, and navigate to your Xcode Project Directory that you created.
- Write the following command.
pod init
- After running this command you will see a file named Podfile in your project directory. Open this file with any Text Editor I am using Sublime.
- Modify the file’s code as below and save the file.
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'FirebaseExample' do pod 'Firebase/Auth' end
- We have added Firebase Auth, as we only need this for this tutorial. Now again run the following command in terminal.
pod install
- The firebase dependencies will be added to your project.
- Now go inside your project directory and open YourProjectName.xcworkspace, in my case it is FirebaseExample.xcworkspace.
Creating User Interface for Registration
- In your project click on Main.storyboard and design the following screen.
- The above design is very simple as we are using Two Text Field, One Label and One Button. In the Text Field user will enter email and password. Label is for displaying message and finally a Button for user to perform registration.
Connecting Views to Code
- Now open assistant editor and connect all the views to your code. If you don’t know how to do this you can go back to previous Text Field and Button Tutorial.
- After connecting the views get the email and password on Button Click. The code for your ViewController.swift will be.
// // ViewController.swift // FirebaseExample // // Created by Belal Khan on 03/10/16. // Copyright © 2016 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController { //Textfields for email and password @IBOutlet weak var textFieldEmail: UITextField! @IBOutlet weak var textFieldPassword: UITextField! //label for displaying message @IBOutlet weak var labelMessage: UILabel! //button for registration @IBAction func buttonRegister(sender: UIButton) { //do the registration operation here //first take the email and password from the views let email = textFieldEmail.text let password = textFieldPassword.text } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Performing Firebase User Registration
In 3 simple steps we can do firebase user registration
- Import Firebase, for this write the following code.
//importing firebase import Firebase
- Initialise Firebase, for this go inside the method viewDidLoad() and write the following line.
//initialising firebase FIRApp.configure()
- Perform User Registration, for this we can use the following code.
FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user: FIRUser?, error) in if error == nil { //registration successful }else{ //registration failure } })
Completing the Code
- So the final code after doing all the required stuffs in ViewController.swift will be.
// // ViewController.swift // FirebaseExample // // Created by Belal Khan on 03/10/16. // Copyright © 2016 Belal Khan. All rights reserved. // import UIKit //importing firebase import Firebase class ViewController: UIViewController { //Textfields for email and password @IBOutlet weak var textFieldEmail: UITextField! @IBOutlet weak var textFieldPassword: UITextField! //label for displaying message @IBOutlet weak var labelMessage: UILabel! //button for registration @IBAction func buttonRegister(sender: UIButton) { //do the registration operation here //first take the email and password from the views let email = textFieldEmail.text let password = textFieldPassword.text FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user: FIRUser?, error) in if error == nil { self.labelMessage.text = "You are successfully registered" }else{ self.labelMessage.text = "Registration Failed.. Please Try Again" } }) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //initialising firebase FIRApp.configure() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Testing The Application
- Now just run the application in Simulator.
- You can see we got the success message. Now lets check the Firebase Console for the registered user.
- You can see the registered user in Firebase Console. So our application is working absolutely fine.
- If you are facing any problem you can have my source code from the link given below.
[sociallocker] Firebase iOS Tutorial - User Registration (902 downloads) [/sociallocker]
So thats all for this post friends. In the upcoming post for this Firebase iOS Tutorial Series I will be covering more firebase services. And don’t hesitate to ask in the comment section if having any confusion regarding this Firebase iOS Tutorial. Thank You 🙂
malcolm says
Great tutorial thanks, but it needs updating for the latest version on Firebase.
Ingo Ngoyama says
Needs an up date but it is perfect with precise detail. I love it.
nany says
thank u for the great tutorial, i want to ask u about if i can add a database with Auth on same pod file then i make (pod install for the database)?
this right a way?
Sebastian says
Hi,
For some reason I am getting this error message: unrecognized selector sent to instance
I am using Xcode 9.2 with Swift 3.2
Can you help me?
Baguafit says
Xcode 9 – Swift 4
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
@IBOutlet weak var textFieldEmail: UITextField!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var labelMessage: UILabel!
//MARK: Action
@IBAction func buttonSignin(_ sender: UIButton) {
// do sign in operation here. Note this function was not in the tutorial
if let email = textFieldEmail.text, let pass = textFieldPassword.text {
Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in
//print(“\(car) has a licence: \(license)”)
if error == nil {
self.labelMessage.text = “UserID ” + Auth.auth().currentUser!.uid + ” sign in successful”}
else {
self.labelMessage.text = “Signin Failed.. Please Try Again”
}
})
}
}
@IBAction func buttonRegister(_ sender: UIButton) {
// do the registration operation here
if let email = textFieldEmail.text, let pass = textFieldPassword.text {
Auth.auth().createUser(withEmail: email, password: pass, completion: { (authResult, error) in
if error == nil {
self.labelMessage.text = “You are successfully registered”
}else{
self.labelMessage.text = “Registration Failed.. Please Try Again”
}
})
}
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}