Sådan får du push-beskeder, der arbejder med Ionic 4 og Firebase

En komplet trinvis vejledning, der får dig på rette spor til iOS og Android

Opsætning af push-underretninger kan være virkelig frustrerende og tidskrævende. Så jeg gennemgik alle opsætningerne og forberedte denne vejledning til dig.

Forudsætning

Ionic 4 skal allerede være installeret.

Sektionsnavigation

  1. Pakkeinstallation
  2. Firebase-opsætning til Android og iOS
  3. Implementering af push-underretningskode
  4. Test push-meddelelser på Android
  5. Forudinstallation af iOS-push-underretning
  6. Test push-meddelelser på iOS

1. Pakkeinstallation

Åbn dit Ionic-projekt i kodningseditoren efter eget valg, og åbn også din terminal. Naviger til projektets mappe.

Først installerer vi alle de nødvendige pakker.

Hvad vi skal installere:

  • Cordova-plugin til firebase:ionic cordova plugin add cordova-plugin-firebase
  • Firebase native-pakke: da Ionic 4 er i beta, skal du kontrollere dine Ionic-native-pakker i package.json og installere den samme version som andre Ionic-native-pakker. Lad os endelig skrive:npm install --save @ionic-native/[email protected]
  • En sidste pakke, AngularFire 2 . Dette er et bibliotek til Angular og Firebase:npm install --save angularfire2 firebase

Pakker installeret, færdig! Lad os gå til det andet afsnit.

2. Firebase-opsætning til iOS og Android

Før vi starter hele opsætningen, skal jeg advare dig om, at du ikke kan teste dine push-underretninger på iOS-emulator. For at teste det skal du have en Apple Developer-konto, der koster omkring $ 99USD om året. Jeg foreslår, at du alligevel gennemgår iOS-opsætningen, så det giver dig en bedre forståelse for fremtidige projekter.

Bemærk: De trin, der starter her, er meget vigtige, så vær tålmodig. Læs langsomt og sørg for at få alt rigtigt. At lede efter problemer efter alt opsætningen kan være meget frustrerende, stol på mig - jeg taler ud fra min egen erfaring.

iOS

Naviger til Firebase-siden, og log ind på en konsol. Hvis du ikke har oprettet et projekt endnu, skal du gøre det nu. Du skal se denne skærm.

Klik på iOS-knappen, så ser du dette:

Nu skal vi give vores iOS-bundt-id, og dette skal være det samme som i dit ioniske projekt. Lad os sige, at jeg vil have bundtnavnet com.filipjerga.angularcourse, så skal jeg gøre følgende:

Åbn dine Ionic-projekter, og naviger til filen "config.xml". Lad os inspicere widgetelementet. Den Id attribut holder den entydige identifikator for din ansøgning . Jeg sagde før, hvis du specificerede dit com.filipjerga.angularcoursebundtnavn i Firebase, skal id'et i dit ioniske projekt være det samme! Du kan også lade id'et ligesom du allerede har det i dit ioniske projekt, men så skal du ændre det i Firebase.

Når du har fået værdien af id, skal du ikke glemme at give den til din Firebase-applikation som bundt-id'et.

Det skal være alt i det første trin med at registrere applikationen. Dette trin er afgørende, så dobbelttjek værdien af id på widget og bundt-id i din Firebase-applikation .

Lad de andre felter være tomme, og klik på "Registrer app".

Nu skal vi downloade "GoogleService-Info.plist".

Når det er downloadet, skal du indsætte det i en basemappe på dine projekter. Du kan se en mappestruktur i mit projekt her.

Vi kan springe alle de yderligere trin over, da de ikke er nødvendige for opsætningen af ​​det ioniske projekt. Du skal have din IOS-applikation klar.

Android

Følgende trin til Android er næsten de samme som for iOS-opsætningen:

  • Klik på 'tilføj app' til Android, det samme som vi gjorde i iOS før.
  • Android-pakkens navn skal være det samme som vores widget-id, i mit tilfælde: 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 et komplet projekt se min Github Repo.

Glad kodning!

Filip