기본 콘텐츠로 건너뛰기

Push Notification using Ionic 4 and Firebase Cloud Messaging

Push Notification using Ionic 4 and Firebase Cloud Messaging

https://www.djamware.com/post/5c6ccd1f80aca754f7a9d1ec/push-notification-using-ionic-4-and-firebase-cloud-messaging#setup-google-fcm

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM)

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM). We will use Ionic 4 Cordova native FCM plugin for receiving a push notification and using Firebase API for sending push notification from the Postman. A few years back, we have created a tutorial on receiving push notification using Firebase Cloud Messaging with Ionic 2.

Shortcut to the steps:

Google said that notification is a message that pops up on the user's device. Notifications can be triggered locally by an open application, or they can be "pushed" from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customized content. In this tutorial, the message sent from the Firebase via API using Postman. Then receive by Ionic 4 mobile apps using Ionic Cordova Native FCM plugin.

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version 4.10.3

You watch the video version of this tutorial on our YouTube channel.

Setup and Configure Google Firebase Cloud Messaging (FCM)

We are using Firebase Cloud Messaging (FCM) because it's a cross-platform messaging solution that lets you reliably deliver messages at no cost. Open your browser then go to Google Firebase Console then log in using your Google account.

Next, click on the Add Project button then fill the Project Name with `Ionic 4 FCM` and check the terms then click Create Project button.

After clicking the continue button you will redirect to the Project Dashboard page. Click the Gear button on the right of Project Overview then click Project Settings. Click the Cloud Messaging tab the write down the Server Key and Sender ID for next usage in the API and Ionic 4 App. Next, back to the General tab then click the Android icon in your Apps to add Android App.

Fill the required fields in the form as above then click Register App button. Next, download the `google-services.json` that will use in the Ionic 4 app later. Click next after download, you can skip Add Firebase SDK by click again Next button. You can skip step 4 if there's no App creating on running yet.

Create a new Ionic 4 App

As usual, we will create a blank Ionic 4 as a starter step. To create a new Ionic 4 App, type this command in your terminal.

ionic start ionic4-push blank --type=angular

If you see this question, just type `N` for because we will installing or adding Cordova later.

Install the free Ionic Appflow SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-push

As usual, run the Ionic 4 App for the first time, but before run as `lab` mode, type this command to install `@ionic/lab`.

npm install --save-dev @ionic/lab ionic serve -l

Now, open the browser and you will the Ionic 4 App with the iOS, Android, or Windows view. If you see a normal Ionic 4 blank application, that's mean you ready to go to the next steps.

Add Ionic 4 Cordova Native FCM Plugin

We will use the latest Google Firebase Cloud Messaging Cordova Push Plugin that also available as an Ionic module. To install Ionic 4 Cordova Native Firebase Message Plugin, type this command.

ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated npm install @ionic-native/fcm

Next, open and edit `src/app/app.module.ts` then add this import of @ionic-native/fcm/ngx.

import { FCM } from '@ionic-native/fcm/ngx';

Add FCM module to `@NgModule` providers.

providers: [ StatusBar, SplashScreen, FCM, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ],

Next, open and edit `src/app/app.component.ts` then add these imports of FCM (@ionic-native/fcm/ngx) and Router (@angular/router).

import { FCM } from '@ionic-native/fcm/ngx'; import { Router } from '@angular/router';

Inject FCM and Router module to the constructor along with other required modules.

constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private fcm: FCM, private router: Router ) { this.initializeApp(); }

Inside platform ready of `initializeApp` function, add a function to get FCM token then print out to the browser console.

this.fcm.getToken().then(token => { console.log(token); });

Add this function to refresh the FCM token.

this.fcm.onTokenRefresh().subscribe(token => { console.log(token); });

Add this function to receive a push notification from Firebase Cloud Messaging (FCM).

this.fcm.onNotification().subscribe(data => { console.log(data); if (data.wasTapped) { console.log('Received in background'); this.router.navigate([data.landing_page, data.price]); } else { console.log('Received in foreground'); this.router.navigate([data.landing_page, data.price]); } });

Above an example of receiving a push notification from FCM will redirect to the other page with params of data. For that, next, we have to add a new page by type this command.ionic g page second

Next, modify `src/app/app-routing.module.ts` then change the new page route.

const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', loadChildren: './home/home.module#HomePageModule' }, { path: 'second/:price', loadChildren: './second/second.module#SecondPageModule' }, ];

Next, open and edit `src/app/second/second.page.ts` then add this import of ActivatedRoute (@angular/router).

import { ActivatedRoute } from '@angular/router';

Inject the ActivateRoute module to the constructor.

constructor(private route: ActivatedRoute) { }

Add a variable for hold data from router parameters.

price: any = '';

Add this line to get data from the router parameters.

constructor(private route: ActivatedRoute) { this.price = this.route.snapshot.params['price']; }

Next, open and edit `src/app/second/second.page.html` then replace all HTML tags with this simple page that shows the simple text.

Second Congratulation! You get price from our sponsor: {{price}}

If you plan to send push notification to the group of the topic, add these lines inside the platform ready.

this.fcm.subscribeToTopic('people');

To unsubscribe from the topic, add this line.

this.fcm.unsubscribeFromTopic('marketing');

Run and Test Sending and Receiving Push Notification

Before running this Ionic 4 app, we have to copy the downloaded `google-services.json` file to the root of the project. Type this command to add the Android platform.

ionic cordova platform add android

Next, copy the `google-services.json` to the `platform/android/` directory.

cp google-services.json platform/android/

Next, run the Ionic 4 App to the Android device by type this command.

ionic cordova run android

After the app running on the device, check the console from the Google Chrome by type this address `chrome://inspect` then choose the inspect link. You should take to the browser inspector, just change to the console tab.

As you can see above, you can take and write down the FCM token for use by Postman. Next, open the Postman application from your computer. Change the method to POST and add this address `https://fcm.googleapis.com/fcm/send`. On the headers, add this key `Content-Type` with value `application/json` and `Authorization` with value `key=YOUR_FIREBASE_KEY...`.

Next, add this JSON data to the RAW body.

{ "notification":{ "title":"Ionic 4 Notification", "body":"This notification sent from POSTMAN using Firebase HTTP protocol", "sound":"default", "click_action":"FCM_PLUGIN_ACTIVITY", "icon":"fcm_push_icon" }, "data":{ "landing_page":"second", "price":"$3,000.00" }, "to":"eadego-nig0:APA91bEtKx9hv50lmQmfzl-bSDdsZyTQ4RkelInfzxrPcZjJaSgDmok3-WQKV5FBu9hrMrkRrcCmf3arkGSviGltg5CyC2F9x1J2m0W7U8PxJ3Zlh7-_tL6VcFdb76hbaLIdZ-dOK15r", "priority":"high", "restricted_package_name":"" }

If you want to send by topics recipients, change the value of `to` to `topics/people`. Next, click the send button and you should see this response.

{ "multicast_id": 7712395953543412819, "success": 1, "failure": 0, "canonical_ids": 0, "results": [ { "message_id": "0:1550632139317442%b73443ccb73443cc" } ] }

And you will see the notification on your Android device background screen.

If you tap on it, it will open the App and redirect to the second page with this view.

That it's, the example of receiving push notification using Ionic 4 and Firebase Cloud Messaging. You can grab the full source code from our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks!

https://www.djamware.com/post/5c6ccd1f80aca754f7a9d1ec/push-notification-using-ionic-4-and-firebase-cloud-messaging#setup-google-fcm

from http://finance2.tistory.com/576 by ccl(A) rewrite - 2020-03-19 11:20:19

댓글

이 블로그의 인기 게시물

[Angular] Router 라우터 정리

[Angular] Router 라우터 정리 Angular2 버전 이후를 기준으로 정리한 글입니다. 라우터는 URL을 사용하여 특정 영역에 어떤 뷰를 보여 줄지 결정하는 기능을 제공한다. 전통적인 서버사이드 렌더링을 하는 웹 사이트는 주소가 바뀔 때마다 서버에 전체 페이지를 요청하고 전체 페이지를 화면에 렌더링한다. 매 요청시 전체 페이지를 새로 랜더링하는 것은 비효율적이기 때문에 라우터를 이용하여 필요한 부분만 랜더링을 한다면 효율적일 것이다. 라우터는 URL에 해당하는 컴포넌트를 화면에 노출하고 네비게이션을 할 수 있는 기능을 가지고 있다. Router 구성 요소 Router – 라우터를 구현하는 객체이다. Navigate() 함수와 navigateByUrl() 함수를 사용하여 경로를 이동할 수 있다. RouterOulet – 라우터가 컴포넌트를 태그에 렌더링하는 영역을 구현하는 Directive이다. Routes – 특정 URL에 연결되는 컴포넌트를 지정하는 배열이다. RouterLink – HTML의 앵커 태그는 브라우저의 URL 주소를 변경하는 것이다. 앵귤러에서 RouterLink를 사용하면 라우터를 통해 렌더링할 컴포넌트를 변경할 수 있다. ActivatedRoute – 현재 동작하는 라우터 인스턴스 객체이다. Router 설정 라우터를 사용하기 위해서는 먼저 Router 모듈을 import 해야 한다. import { RouterModule, Routes } from '@angular/router'; 라우터에서 컴포넌트는 고유의 URL과 매칭된다. URL과 컴포넌트는 아래와 같이 Routes 객체를 설정하여 지정할 수 있다. 아래의 예에서는 디폴트 path에서는 MainComponent가 노출이 되고 product-list path에서는 ProductListComponent가 노출이 되도록 설정을 한 것을 볼 수 있다. const routes: Routes = [ { pa...

(번역)Angular - User Input

(번역)Angular - User Input (번역)Angular - User Input User input triggers DOM events. We listen to those events with event bindings that funnel updated values back into our components and models. User input은 DOM 이벤트를 실행시킵니다. 우리는 그 이벤트들을 component들과 model들에게 업데이트된 값을 제공하는 이벤트 바인딩을 통해 듣습니다. User actions such as clicking a link, pushing a button, and entering text raise DOM events. This page explains how to bind those events to component event handlers using the Angular event binding syntax. 링크나 버튼을 눌러 텍스트를 타고 들어가는 유저들의 액션은 DOM 이벤트를 일으킵니다. 이 페이지는 그러한 이벤트들을 어떻게 Angular syntax를 이용해 component이벤트 핸들러들로 묶을 수 있는지 설명합니다. Binding to user input events User input이벤트에 바인딩하기(묶기) You can use Angular event bindings to respond to any DOM event. Many DOM events are triggered by user input. Binding to these events provides a way to get input from the user. 여러분은 Angular이벤트 바인딩을 어느 DOM이벤트에나 응답하도록 사용할 수 있습니다. 이런 DOM이벤트에 바인딩을 해두면 사용자들로부터 input을 받을 수 있게됩니다. To bind to a DOM event, surround the D...

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증...

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증... django 는 기능이 참 너무 많다 ^^; 지금은 서버는 django로, 프론트는 angular를 붙여서 간단한 웹을 만들어 보려고 한다. 웹 만들때 항상 회원가입/로그인 기능은 맨 앞에 구현한다. 어떻게 구현하면 좋을까... 찾아보다가 이 기능을 구현할 수 있는 방법이 너무 많아서 정보를 찾기 더 어려웠다. 일단 나는 django에서 django rest framework라는 것을 사용해서 API를 만드려고 한다. 순수 django 튜토리얼에는 바로 template 랑 연결해서 설명하는 부분이 많았다. 나는 그냥 API 만 만들고 싶다고!! 그래서 찾은 것이 django REST framework. https://www.django-rest-framework.org/api-guide/authentication django REST framework 설치 using pip pip install djangorestframework settings.py INSTALLED APPS 에 추가해야함 INSTALLED_APPS = [ ... 'rest_framework', ] django REST framework 에서도 인증 관련해서 제공하는 것이 1개가 아닌 여러 개다. 나는 그중에 TokenAuthentication을 이용해서 로그인을 구현해 보려고 한다. TokenAuthentication Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. 이렇게 나와있어서 내가 하려는 것과 일치해서 이걸로 결정 ~ 솔직히 처음 로그인을 구현하려고 하면 도대체 그 과정이 어떻게 되는지 모를 수 도 있다. 나는 쉽게 정리하면 아래와 같은 과정이라고 생각한다. 로그인 로그아웃...