Links

Firebase Integration

Firebase and Ionic Integration. Learn how we use Firebase in Ion2FullApp Ionic Template.
The code for this integration is under the following folder: src/pages/firebase-integration

Set up

We are going to use angularfire2 plugin in order to connect our Ionic 3 application with a Firebase Firestore database.
In order to install the plugin we must run the following command: npm install firebase angularfire2 --save
Now we go to firebase console and start a new project. Once you have created the firebase project you will be redirected to the following screen:
Click on the Add Firebase to your web app button and a pop up with your app credentials will be shown. The pop up will have the following information about your new Firebase App:
The next thing we need to do to connect Firebase to our Ionic project is to add the Firebase app credentials from above in our Ionic project. We will add this credentials in our Ionic project configuration file environment.ts located in src/environment/environment.ts
export const environment = {
production: false,
firebase: {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_SENDER_ID"
}
};

Login

Email/Password

First of all we have to enable email/password login method in the Firebase Console located in Develop => Authentication and then click the Sign-in method tab. For better instructions see the image below.
You can find the login and register methods in: src/pages/firebase-integration/firebase-auth.service.ts
doLogin(value){
return new Promise<any>((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(value.email, value.password)
.then(res => {
resolve(res);
}, err => reject(err))
})
}
doRegister(value){
return new Promise<any>((resolve, reject) => {
firebase.auth().createUserWithEmailAndPassword(value.email, value.password)
.then(res => {
resolve(res);
}, err => reject(err))
})
}

Facebook

First of all we must create a Facebook application in the Facebook developer page.
Once your Facebook App is created you will get an App Id and App Secret Key that will be used later for configuration.
After creating the Facebook application, we go back to the authentication section located in the Firebase console. Then we go to the sign-in methods on the console and enable the Facebook option, for this it is necessary to add the facebook App ID and the App secret key.
Once Facebook is enabled as a login, a valid OAuth redirect URI will be automatically generated, and must be entered in the Facebook Application panel as shown below:
Now we have to add some extra configuration for android and ios platforms.
For Android
  • Add platform android
  • Set your Google Play Package Name. You can find your name in your platforms/android/AndroidManifest.xml file.
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.ionic3FirebaseLogin" xmlns:android="http://schemas.android.com/apk/res/android">
  • Set the Class Name to com.facebook.FacebookActivity
  • Generate your own Key Hash
On OS X, run:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
On Windows, use:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl base64
For IOS
  • Add platform iOS
  • Set your Bundle ID. (You can find your ID in your config.xml file on the root of your project under the tag widget).
<widget id="io.ionic.ionic3FirebaseLogin" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Google

To perform the Google social login authentication in your Ionic 3 application we only need to enable Google login method and follow the SHA1 configuration instructions from the screenshot.

Twitter

Twitter configuration is similar to Facebook configuration. To perform Twitter social login in your Ionic application, you need to create a Twitter application in the Twitter application management console. Just follow the steps to create a new app.
Once your Twitter App is created you will get an ID and Secret Key. Keep them at hand because you will need them later.
After creating the Twitter application, we go back to the authentication section located in the Firebase console. Then we go to the sign-in methods on the console and enable the Twitter option, for this it is necessary to add the Twitter API KEY and the API SECRET.
Once enabled, a callback URL must be automatically generated which must be added in the Twitter application.
In our AuthService we have the functions to perform each social login using Firebase. We are going to implement native login.
Note: If you are testing on browser we are able to login with pop up.

Person CRUD

Once the user is logged in, we show two tabs:
  • Feed (with the CRUD)
  • Profile
In this app you will find all the screens needed for a CRUD (create, read, update and delete).
In this app People will have the following attributes:
  • name
  • nameToSearch
  • surname
  • age
  • avatar
For avatars we have some pictures already loaded on the firebase database which will be used as an avatar. We also added an attribute “nameToSearch” which is the name of the person but in lower case. This will be useful when we make a searching by name. Read Firebase restrictions to learn more.
In src/pages/firebase-integration/firebase-integration.service.ts you will find all the functions to communicate with Firestore database

Filters

We are going to explain how to query data using Firestore. In this example we have two filters:
  • by age
  • by name
You can find the methods to search in src/pages/firebase-integration/firebase-integration.service.ts
searchPeople(searchValue){
return new Promise<any>((resolve, reject) => {
this.afs.collection('people',ref => ref.where('nameToSearch', '>=', searchValue)
.where('nameToSearch', '<=', searchValue + '\uf8ff'))
.snapshotChanges()
.subscribe(snapshots => {
resolve(snapshots);
})
})
}
You will see that in the search by name method we add the \uf8ff character to the end of the search value. \uf8ff character is a very high code point in the Unicode range. Because it is after most regular characters in Unicode, the query matches all values that start with searchValue.

Person Profile

In this tab we will show some information of the logged user like the profile image and full name.
This information will be editable, so we will be able to change the full name and profile image using image picker plugin.

Firebase Restrictions

We found some restrictions with Firebase, for some of them there are “legal” workarounds which we implemented.
When implementing the searching by name functionality, we found some difficulties with Firestore. The first one was that Firestore does not provide a contains function so the searching always filters by the entire name, let see an example:
Imagine we have a person called Robert and the followings cases:
Search: Rob Robert is present in the results
Search: Ber The result is empty because there’s no one which names start with Ber. The solution of this problem can be to implement a contain function that Firestore does not provide.
The second problem we had was that searches are not case sensitive, it means that the results of searching Robert and robert are not equal.
To resolve this problem, we change our database structure and added an extra field on people collection: nameToSearch (this value will be the name on lowercase).
Why we did that? It is simple, now all searching will be on lowercase. Following the above example, now if we search “Robert” we convert it to “robert”.