Easily Integrate Firebase into your iOS Apps

570
SHARES
2.6k
VIEWS

Today we will learn how to integrate firebase into our iOS Applications and make our iOS Apps even smarter 💪. At some point in our development journey, we all need a backend solution for tasks like Realtime Chat, storing User Data, Monitoring Apps and many more scenarios. Firebase is a cloud-based service that provides most of the server-side features for our iOS apps so that we don’t have to manage the infrastructure like databases, servers and server-side things by yourself.

In this tutorial, we will see how to get started with Firebase and see how to configure database and authentication services provided by Firebase. Firebase Provides Features Like

  • Firebase Realtime Database
  • Firebase Authentication
  • Firebase Storage
  • Firebase Remote Config
  • Firebase Cloud Messaging
  • Firebase Notifications
  • Firebase Analytics
  • Firebase Crash Reporting

History of Firebase

So What is Firebase? Firebase was founded by Andrew Lee and James Tamplin in 2011 and launched officially in April 2012. Originally, the system was intended to be a real-time database providing its APIs enabling users to store and sync data across different clients. However, the plans changed a little bit when Firebase was acquired by Google two years later after its release. Today, the Firebase service has a number of functions that really attract every developer.

Setup

Before we start, we need to have a Google Account. With your google account visit https://firebase.google.com/ and log in with your credentials. You can go to the Firebase console where Firebase will ask you to Create a Project with your country. Firebase UI is very friendly and guides you through every step so don’t need to worry about anything once you entered in the console.

Add iOS Application to Firebase

We can then able to add our iOS App to the project by clicking on the Add Firebase to Your iOS App. Now we need to specify the Bundle ID of our iOS app which has to be unique. I have created a com.codemeals.XCTalk identifier for our demo project.

Setup Config File

Firebase creates a file called GoogleService-Info.plist file which we need to add to our Xcode project, just near to Info.plist file. Don’t forget to select Copy items if needed and Create folder references.

Setup CocoaPods

Now we have to setup CocoaPods that come up with Firebase.

We just need Firebase Database and Authentication so add those to Podfile and then install the pod using the pod install command.

pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Database'

Register Firebase with App

The last step is to connect our iOS app to Firebase. Simply add the code to your AppDelegate.Swift file to use Firebase in our App and press Next.

Setting up Firebase Database

Now that, we have done all the setup for the iOS app to use Firebase Database and Authentication. Let’s try to create the database and add a fake message to test that connection is working.

Test Connection

Let’s add the following code in the AppDelegate.Swift file just below where we have configured Firebase i.e FirebaseApp.configure()

let db = Database.database().reference()
db.setValue("Hi Firebase")

Now run the app and see if you can write to Firebase Database.

Probably not, you will get a permission denied error in the Xcode console which indicates that we need to allow permission for our app to write to Firebase. So head over to firebase console and Select Database service and Rules and change it to something like this

{
"rules": {
".read": true,
".write": true
}
}

We are basically allowing everyone to write to the database for now. If you run the app, you can see that your message has been logged in the Cloud database.

Add Data to the Firebase Database

We probably need to add more complex stuff to the database, not the just hello message. Let’s consider your app has UI to add messages and we are adding messages and sender info to the Firebase. We can create a child database and add it using code looks something like this:

let messagesDB = Database.database().reference().child("Messages")
        
let messageDictionary : NSDictionary = ["Sender" : Auth.auth().currentUser!.email as String!, "MessageBody" : messageTextfield.text!]        messagesDB.childByAutoId().setValue(messageDictionary) {
            (error, ref) in
            if error != nil {
                print(error!)
            }
            else {
                print("Message saved successfully!")
            } 
       }

Fetch Data from Firebase Database

We can also fetch the data from the firebase database. Let’s see how to retrieve the sender and the messages that we saved to the firebase database. We can do more complex operations on the database.

let messageDB = Database.database().reference().child("Messages")

messageDB.observe(.childAdded, with: { snapshot in

let snapshotValue = snapshot.value as! NSDictionary
let text = snapshotValue["MessageBody"] as! String
let sender = snapshotValue["Sender"] as! String
}

Firebase Authentication

Firebase has also used for authentication services like login and registration. Before diving into the authentication service code, we need to enable the authentication from Firebase console. From the console, select the Authentication tab and SIGN-IN METHOD and select the method we want to use for sign-in users. But for this example, we will select the email/password method.

User Registration

We can easily register a user using firebase methods createUser like this

Auth.auth().createUser(withEmail: emailTextfield.text!, password: passwordTextfield.text!, completion: { (user, error) in
if error != nil {
print(error!)
}
else {

print ("Registration Successful!")
}

Now Firebase will handle all the registration stuff automatically.

User Login/SignIn

Firebase recognizes the registered user and allows them to sign in using the signIn method.

Auth.auth().signIn(withEmail: emailTextfield.text!, password: passwordTextfield.text!, completion: { (user, error) in
            if error != nil {
                print(error!)
            }
            else {
                
                print("login was successful")
}

Signing Out User

Firebase also has the method to log out users. It has a signOut method which can be used like this

do {
try Auth.auth().signOut()
}
catch {
print(error)
print("error: there was a problem logging out")
}

As you can see how easy it is to use Firebase for registering users to the app.

There are many other services that Firebase provides for the iOS apps but we will have to stop here as you might have a basic understanding of how Firebase works in general.

Final Words

Using Cloud-based services like Firebase, we can simplify a lot of the development activities for both web and mobile and develop applications much faster. However, you have to find the perfect balance of how much you depend on service like Firebase. What is your experience of using Firebase in production Apps? Let me know in the comment.

Best resources to learn firebase

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending