Как получить push-уведомления, работающие с Ionic 4 и Firebase

Полное пошаговое руководство, которое поможет вам встать на правильный путь для iOS и Android.

Настройка push-уведомлений может быть по-настоящему утомительной и отнимать много времени. Итак, я прошел через все настройки и подготовил для вас это руководство.

Предпосылка

Ionic 4 уже должен быть установлен.

Навигация по разделам

  1. Установка пакета
  2. Настройка Firebase для Android и iOS
  3. Реализация кода push-уведомлений
  4. Протестируйте push-уведомления на Android
  5. Предварительная настройка push-уведомлений iOS
  6. Протестируйте push-уведомления на iOS

1. Установка пакета

Откройте свой проект Ionic в редакторе кода по вашему выбору, а также откройте свой терминал. Перейдите в папку вашего проекта.

Сначала мы установим все необходимые пакеты.

Что нам потребуется для установки:

  • Плагин Cordova для firebase:ionic cordova plugin add cordova-plugin-firebase
  • Собственный пакет Firebase: поскольку Ionic 4 находится в package.json стадии бета-тестирования, проверьте свои собственные пакеты Ionic и установите ту же версию, что и другие пакеты с родным Ionic. Наконец, введите:npm install --save @ionic-native/[email protected]
  • Последний пакет, AngularFire 2 . Это библиотека для Angular и Firebase:npm install --save angularfire2 firebase

Пакеты установлены, готово! Переходим ко второму разделу.

2. Настройка Firebase для iOS и Android.

Прежде чем мы начнем всю настройку, я должен предупредить вас, что вы не можете тестировать свои push-уведомления на эмуляторе iOS. Чтобы проверить это, вам понадобится учетная запись Apple Developer, которая стоит около 99 долларов США в год. Я предлагаю вам в любом случае пройти настройку iOS, чтобы вы могли лучше понять будущие проекты.

Примечание . Шаги, которые начинаются здесь, очень важны, поэтому проявите терпение. Читайте медленно и убедитесь, что все поняли правильно. Поиск проблем после всей настройки может быть очень неприятным, поверьте мне - я говорю из своего собственного опыта.

iOS

Перейдите на страницу Firebase и войдите в консоль. Если у вас еще нет проекта, сделайте это сейчас. Вы должны увидеть этот экран.

Нажмите на кнопку iOS, и вы увидите это:

Теперь нам нужно предоставить идентификатор нашего пакета iOS, и он должен быть таким же, как в вашем проекте Ionic. Скажем, я хочу получить имя пакета com.filipjerga.angularcourse, тогда мне нужно сделать следующее:

Откройте свои проекты Ionic и перейдите к файлу config.xml. Давайте проверим элемент виджета. Id атрибут содержит уникальный идентификатор вашего приложения . Я уже говорил, что если вы указали имя своего пакета com.filipjerga.angularcourseв Firebase, идентификатор в вашем проекте Ionic должен быть таким же! Вы также можете оставить идентификатор, который у вас уже есть в вашем проекте Ionic, но затем вам нужно изменить его в Firebase.

После того, как вы получите значение id, не забудьте предоставить его приложению Firebase в качестве идентификатора пакета.

That should be everything in the first step of registering the application. This step is crucial, so double check the value of id on the widget and bundle ID of your Firebase application.

Leave the other fields blank and click “Register app”.

Now we need to download “GoogleService-Info.plist”.

When it’s downloaded, paste it into a base folder of your projects. You can see a folder structure in my project here.

We can skip all of the further steps, as they are not required for the Ionic project setup. You should have your IOS application ready.

Android

The following steps for Android are almost the same as for the iOS setup:

  • Click ‘add app’ for Android, same as we did in iOS before.
  • The Android package name needs to be the same as our widget id, in my case: com.filipjerga.angularcourse
  • Next, download google-services.json. Same as before with the iOS file, we need to copy it to the base folder of our applications
  • Click “Next” until you are on the last step, which you can skip, and you should end up with both applications created.

Yay! Congrats! But it’s still too early to cheer.

3. Push notification code implementation

Package importing

The time has come to finally warm up our fingers by typing some code. We will start with importing the packages we installed before.

  1. Go to app.module.ts
  2. Your file should look like this:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AngularFireModule } from 'angularfire2'; import { AngularFirestoreModule } from 'angularfire2/firestore'; import { Firebase } from '@ionic-native/firebase/ngx'; const config = { apiKey: "AIzaSyD-K6SlFECXKmd8iHwEvggVtavKgyPF2k8", authDomain: "angular2-course-9270e.firebaseapp.com", databaseURL: "//angular2-course-9270e.firebaseio.com", projectId: "angular2-course-9270e", storageBucket: "angular2-course-9270e.appspot.com", messagingSenderId: "443316848633" }; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [ BrowserModule, IonicModule.forRoot(), AppRoutingModule, IonicStorageModule.forRoot(), AngularFireModule.initializeApp(config), AngularFirestoreModule], providers: [ StatusBar, SplashScreen, Firebase, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}

You can see Firebase in the providers array, and AngularFirestoreModule and AngularFireModule in imports.

But where did the config object came from ? You can see lot of information there as “apiKey, authDomain” and so on.

To answer this we need go back to our Firebase console and create a web app.

You need to click on a web platform icon on the right from the Android icon (see the image above). When the web app is selected you will be presented with your own config object.

Now it’s time to copy whole config object to app.module.ts in our Ionic projects. Please make sure you change it for your config object! Mine will not work for you.

Now we can start working on the implementation of the push notification service.

Push notification service

Let’s create a new service. Call it what you like. I will call mine fcm.service.ts. FCM stands for Firebase Cloud Messaging.

First, let’s take a look at the service implementation. I will explain it line by line.

import { Injectable } from '@angular/core'; import { Firebase } from '@ionic-native/firebase/ngx'; import { Platform } from '@ionic/angular'; import { AngularFirestore } from 'angularfire2/firestore'; @Injectable() export class FcmService { constructor(private firebase: Firebase, private afs: AngularFirestore, private platform: Platform) {} async getToken() { let token; if (this.platform.is('android')) { token = await this.firebase.getToken(); } if (this.platform.is('ios')) { token = await this.firebase.getToken(); await this.firebase.grantPermission(); } this.saveToken(token); } private saveToken(token) { if (!token) return; const devicesRef = this.afs.collection('devices'); const data = { token, userId: 'testUserId' }; return devicesRef.doc(token).set(data); } onNotifications() { return this.firebase.onNotificationOpen(); } }

If we want to send a push notification to a device, we need to get an unique identifier of the device. In this case it’s called a token.

We need to check for a platform specific device, because of an additional step in the iOS setup. iOS requires explicit permissions to receive push notifications.

Now we need to store this token somewhere, but where? We will store tokens in the Firebase database. You can see, I am creating device collections and I am filling them with datathat contains the token and just a testing UserId. Perfect! Now, we have stored our token and we can subscribe to notifications.

Subscribing to notifications is actually very simple. We just need to call this.firebase.onNotificationOpen()

Amazing. Service checked!

All of this is nice but kinda useless, since we are not using our service yet. Let’s fix it!

Move to your app.component.tsand write the following:

import { Component } from '@angular/core'; import { Platform } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { FcmService } from './shared/service/fcm.service'; import { ToastService } from './shared/service/toast.service'; import { ToastController } from '@ionic/angular'; @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent { constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private fcm: FcmService, private toastr: ToastService, public toastController: ToastController ) { this.initializeApp(); } private async presentToast(message) { const toast = await this.toastController.create({ message, duration: 3000 }); toast.present(); } private notificationSetup() { this.fcm.getToken(); this.fcm.onNotifications().subscribe( (msg) => { if (this.platform.is('ios')) { this.presentToast(msg.aps.alert); } else { this.presentToast(msg.body); } }); } initializeApp() { this.platform.ready().then(() => { this.statusBar.styleDefault(); this.splashScreen.hide(); this.notificationSetup(); }); } }

Especially important here is the function notificationSetup.

We are getting an unique token of the device first.

We are also subscribing to incoming notifications from Firebase.

When the message is received, we need to check, again, for specific platforms. On iOS your message text is under aps.alert . On Android it’s under body.

Then we will just simply display the received message as a Toast.

Now the code setup is done. We are getting very close! It’s time to test it out.

4. Test push notifications on Android

All of the required setup for Android should be done right now. You can start emulating your app by:

ionic cordova emulate android

or

ionic cordova build android and open your build manually in Android Studio.

Let’s launch our applications and go to a Home menu, so we will see a push notification there. Make sure your application was launched properly in emulator and you have no errors.

Go back to your browsers to your Firebase Applications. Now it’s time to inspect our Firebase Database. You can find the database option in the left panel under the Develop category.

After your application was launched in emulators, the code from app.component.ts we wrote a few moments ago ran. No wonder our database is populated. In the “saveToken” function we specified the “devices” collection and we saved the token with the user id as a document into this devices collection. That is what we see in our database.

In my case, I have multiple tokens in my database but you should have only one since we’ve run our app the first time. You will create a new document per unique device/emulator you are running your app on.

Now it’s time to copy this token in order to send push notification to a specific device.

Navigate to the left panel to a grow tab and click on cloud messaging.

Now we need to fill in the necessary data. Enter the text of your message and provide the token of the device from the database we just copied.

When you are sending a message, open your emulated device simultaneously and watch what happens.

Send a message, aaaaand Congrats! Now your Android setup is done and you are able to send push notifications! Isn’t that awesome?

5. iOS push notification pre-setup

Buckle up guys, iOs setup is coming. Let’s separate this setup into multiple steps, so we will not have a panic attack. Let’s dig in!

First, build your application for iOS: ionic cordova build ios

Open your Xcode, and find your built app in platforms/ios/nameofyourapp.xcodeproj . Open it.

This should open a tree structure of your application on the left side. Double Click the root file of this structure. This will open an additional menu with more settings for your app.

Sign in with your developer account.

5. Open the top “Capabilities” tab and enable “Push Notifications”.

6. Navigate to your Apple developer account page. Under “Certificates” select “All” and click "+" to add a new certificate.

Enable the Apple Push Notification service and proceed to the next step.

Now let’s choose your application.

We need to request a certificate. On your Mac, go to “Keychain Access” -> “Certificate Assistant” -> “Request a Certificate From a Certificate Authority”.

Complete all the necessary information — your email and common name — and save it to disk.

In the Apple Console proceed to the next step and upload your certificate request.

In the next step your certificate should be created and you can download it. You will need it later.

Now we need to create a service key to enable Apple push notifications. Under “Keys” select “All” . Choose your key name. Enable “Apple Push Notifications service (APNs)”.

Click “Continue” and confirm your key. Never share such data with others. You can now download your key.

Now we need to go back to Firebase.

In Firebase, open your iOS application and navigate to “Cloud Messaging”.

We need to upload our APN Authentication Key we generated a while ago. Click “Upload”.

Provide all the information and upload the key.

First, upload your “.p8” file, downloaded from the Apple console earlier. Enter your Key ID. You can get the App ID prefix from the Apple console in “Identifiers”->“App IDs”->“Your App”->“Prefix”.

That’s it. Tears of joy are running down my face.

We can test Push Notifications on iOS. Let’s not forget we need to use a real device.

6. Test push notification on iOS

First, we need to build our applications so let’s run: ionic cordova build ios

In Xcode you can run your application on a device connected by USB with your computer.

Let’s wait until everything is launched. We can now repeat the steps to send push notifications from Section 4, because it is the same as on Android.

Remember that you need to use a new token now, that was generated for your iOS device. Go to Databases, get a new token, and send a push notification. Your result should look like this.

I hope you have been successful with setting up your push notifications. It takes some time and patience to get everything right, but the outcome and benefits are amazing.

If you like my tutorial and you are interested in more, you can check out my course on Udemy: Ionic 4 Crash Course with Heartstone API and Angular.

For a full project see my Github Repo.

Happy Coding!

Filip