기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

[aws] deploy Angular app with s3 | AWS S3로 angular 앱 배포하기

[aws] deploy Angular app with s3 | AWS S3로 angular 앱 배포하기 angular project를 빌드한다 ng build --prod 그러면 dist 폴더가 생긴다. dist 폴더 안에 있는 아이들을 사용한다. 아마존 s3 콘솔로 이동 https://s3.console.aws.amazon.com/s3/home?region=ap-northeast-2 새로운 Bucket 을 생성한다(Create bucket). 버킷 이름은 고유하게 짓는다. 버킷 생성후 properties tab > static website hosting을 클릭한다. index document는 index.html은 쓴다. properties > static website hosting Permission tab 에서 권한을 수정한다. overview tab 에서 필요한 파일 업로드 dist 폴더 안에 있는 파일들을 업로드 한다. bucket policy 설정 properties > static website hosting > endpoint 클릭하면 서버에 올라간 앱을 확인 할 수 있다 일단 angular 앱을 올리긴 했는데.. 이걸로는 아무것도 할 수 었다. django로 만든 서버를 올리고 database를 연결하고 그것을 지금 이 angular 앱과 연결해야한다. 아직 어떻게 해야 할지는 모르겠음 계속 삽질 중. 그래도 angular app 하나 올라갔는데 재밌네 from http://paigeblog.tistory.com/18 by ccl(A) rewrite - 2020-03-25 16:20:22

[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. 이렇게 나와있어서 내가 하려는 것과 일치해서 이걸로 결정 ~ 솔직히 처음 로그인을 구현하려고 하면 도대체 그 과정이 어떻게 되는지 모를 수 도 있다. 나는 쉽게 정리하면 아래와 같은 과정이라고 생각한다. 로그인 로그아웃

(주)편두리 채용 정보: PYUNDOORI에서 핫한 개발자분들을 모십니다.

(주)편두리 채용 정보: PYUNDOORI에서 핫한 개발자분들을 모십니다. - 좋아요 아래와 같은 업무를 훌륭히 감당하실 분을 모십니다.서비스 관련 DB 모델링, DB 최적화 작업서버 & DB 관리Frontend & Backend 인터페이스의 최적화 작업 화합과 성장을 같이! - Angular JS의 경험 - Node.js - javascript 능숙자 - DRMS 사용 능숙자 더 많은 내용은 더 많은 내용은 더팀스 에서 확인하세요! from http://theteams.tistory.com/742 by ccl(A) rewrite - 2020-03-22 12:20:20