A Quick Guide to Firebase: An Innovation in Mobile App Development
Learn about Google's Firebase, a backend-as-a-service providing a real-time database to enable mobile app development for Android and more.
Join the DZone community and get the full member experience.
Join For FreeFirebase is a Backend-as-a-Service (BaaS) for mobile and web to build powerful apps. It was launched by Google to support web-based backends. Initially developed as a YC11 startup, it further developed into a next-generation app on Google Cloud Platform.
What Is the Purpose of Firebase?
Firebase aims at offering a real-time database as well as backend as a service. It stores JSON data in a real-time database. The BaaS provides application developers an application programming interface (API), enabling app data to coordinate via clients stored on the Firebase cloud messaging server. If there's a change in the database, that is also synchronized across the clients and devices using the same database.
Firebase liberates developers to focus on making impressive client experiences. You do not have to manage servers or write APIs. Firebase is like your server, your API, and your data store, where everything that is written can be modified or changed as per your needs.
How to Create a Firebase Account
First, create a Firebase account here. By clicking on the plus icon, you can add your project. You can even create a demo account where authenticated users can add or delete products. Second, you can upload the picture of a client to storage. With this, you will be able to see the users present online.
After adding projects in the Firebase Google console, you will be navigated to the dashboard. Here, you will see a list where the features of the dashboard are mentioned. Further, a small description is also given related to projects.
Features of Firebase
Real-Time Database
A real-time database has no Structured Query Language (SQL). Here, data is stored and synced as a JSON design in real time to every customer connected. All the customers using Android, iOS, or JavaScript share a single database. Changes made in the client's application are synchronized with the real-time database automatically, which works in offline mode.
ref = Database.database().reference(withPath: “grocery-items”)
Now, we create a new example for a new product item.
let productItemRef = self.ref?.child(text.lowercased())
productItemRef?.setValue([
“name”: text,
“addedByUser”: self.user.email,
“completed”: false
])
It will add or synchronize the item to the Firebase console, as shown below. The next step is to reload and upload the view. While adding, updating, or deleting a product in the database, the initialized closure will always give a call.
ref?.queryOrdered(byChild: “completed”).observe(.value, with:
{ snapshot in
var newItems: [GroceryItem] = []
for item in snapshot.children {
let groceryItem = GroceryItem(snapshot: item as!
DataSnapshot)
newItems.append(groceryItem)
}
self.items = newItems
self.tableView.reloadData()
})
Two more products are added in this observer. We got every value, even the new or updated ones, and then we reloaded.
Hosting
Hosting is considered a simple process in Firebase app development. Three new features are involved here - custom domain support free, Global CDN, and auto-provisioned SSL certs. You can easily deploy the applications once the Firebase CLI is installed and set up. It is easy to host your site or app.
# install the CLI
npm install -g Firebase-tools
# login
Firebase login
# start a project
Firebase init
# run locally
Firebase serve
# DEPLOY!
Firebase deploy
Authentication
Many applications require users' identity to fetch and save important information related to them. Firebase Authentication gives backend services, which are easy to use. Also, instant libraries are provided to validate clients of your application.
It supports confirmation of your app's users through the following methods:
Google
Email and password
Phone numbers
Facebook
Twitter
With the help of Firebase Authentication, one can easily build a secure system and improve the sign-in and onboarding experience for end users.
Given below is the code to handle social authentication with the help of the new SDK:
// grab the twitter auth provider
var provider = new Firebase.auth.TwitterAuthProvider();
// do the login
Firebase.auth().signInWithPopup(provider).then(function(result) {
// twitter token and secret you can use to contact the twitter api
var token = result.credential.accessToken;
var secret = result.credential.secret;
// user info
var user = result.user;
}).catch(function(error) {
// blah blah errors
});
Storage
You can upload or download files such as video, photos, or pdf into Google cloud storage. Firebase offers a simple and quick framework for cloud storage. You need to create the instance for storage first, as given below:
func uploadImageForUser(image: UIImage) {
guard let imageData = UIImageJPEGRepresentation(image, 0.8)
else { return }
let imagePath = Auth.auth().currentUser!.uid +
“/\(Int(Date.timeIntervalSinceReferenceDate *
1000)).jpg”
let metadata = StorageMetadata()
metadata.contentType = “image/png”
Storage.storage().reference().child(imagePath).putData(imageDat
a, metadata: metadata) { (metadata, error) in
if let error = error {
}
print(“Error uploading: \(error)”)
return
let changeRequest =
Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.photoURL = metadata?.downloadURL()
changeRequest?.commitChanges { (error) in
print(“User Changed”)
}
}
}
Analytics
Firebase Google Analytics is a free and unlimited analytics solution. It offers you unlimited reporting for up to 500 different events that can be defined using the Firebase SDK. These analytics reports help in knowing how your users behave, helping you make informed decisions related to app marketing and performance optimizations.
Notification
Using Firebase cloud messaging (FCM), a client receives a notification on the app whenever new mail or any data is synced. Notification messages can be sent to drive user retention and re-engagement.
Dynamic Links
Active links are links or URLs which can work as per your requirements. You can create the link via the Firebase console or through the application, which has lots of hidden features and data. If the user clicks on the link via a website, it will direct them to the related content on your local app or site. If the application is not installed, then you will be directed either to the Play Store or the App Store. Once the installation is done, you will able to open the page or link.
Remote Configuration Variables for Apps
Remote configuration instantly allows developers to change the functionality of the app without uploading a new version. This means that you do not have to wait for a long process to get new data for your applications. Below are the steps for how to use Remote Configuration in your app:
- Include Firebase in your app
- Get the Remote Configuration singleton object
- Set in-app default parameter values
- Get parameter values to use in your app
- Set parameter values accordingly in the Remote Config service
- Fetch and activate values accordingly from the Remote Config service
AdMob
AdMob is an easy way to monetize mobile apps with targeted in-app advertising. With the help of Google Analytics, one can drive installs, gain deep insights into ad conversions, and run targeted ad campaigns to engage the user base for a Firebase audience. While linking Firebase and AdWords, you get access to control tools to help you see how your AdWords investment drives app installs and in-app actions. You can even export and import the audience and event list from Analytics to AdWords.
Conclusion
Firebase is an impressive, far-reaching platform for app development that streamlines various tasks to produce quality software solutions. It will surely give tough competition to companies providing web services because it is backed by Google.
Published at DZone with permission of , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments