기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

SPA (Single-page Application)

SPA (Single-page Application) 데스크탑에 비해 성능이 낮은 모바일에 대한 니즈가 증가하면서 스마트폰을 통해 웹페이지를 출력하기 위해서는 기존 방식과는 다른 접근이 필요해졌다. 이를 위해 등장한 기법이 바로 SPA이다. Single-page application (SPA) 서버로부터 완전한 새로운 페이지를 불러오지 않고 현재의 페이지를 동적으로 다시 작성함으로써 사용자와 소통하는 웹 애플리케이션이나 웹사이트 SPA에서 HTML, JavaScript, CSS 등 필요한 모든 코드는 하나의 페이지로 불러오거나, 적절한 자원들을 동적으로 불러들여서 필요하면 문서에 추가하는데, 보통 사용자의 동작에 응답하게 되는 방식이다. SPA와의 소통은 웹 서버와의 동적인 통신을 수반하기도 한다. 이러한 접근은 연속되는 페이지들 간의 사용자 경험의 간섭을 막고, 애플리케이션이 더 데스크톱 애플리케이션처럼 동작하도록 만들어준다. 예를 들어 보통 웹 사이트처럼 여러 페이지가 있고 로그인, 회원가입, 글쓰기 등 복잡한 기능을 지원하지만, 이는 처음 호출된 HTML 상에서 필요한 데이터만 호출하여 화면을 새로 구성해 주는 것으로 실제로 페이지의 이동이 일어나지 않는다. 기존의 웹 사이트는 내용이 변하지 않아도 페이지를 이동할 때마다 서버에서 코드를 생성해 새로 읽고 클라이언트에서는 이 코드를 페이지에 렌더링하게 된다. SPA에서는 이러한 부분들이 처음 웹 사이트 접속 시 한 번만 요청되고 페이지를 이동할 때는 변경되는 view 부분만 데이터를 받아서 렌더링하기 때문에 속도가 빠르다. 불필요한 코드 요청이 줄어 처리량과 트래픽이 적어진다. 물론 SPA에도 단점은 있다. Google 같은 검색 엔진은 SPA를 색인화하는 데 어려움을 겪는다. 한 페이지 내에서 모든 동작을 진행하다 보니 URL이 변경되지 않아 검색의 색인이 어렵다. 대표적인 라이브러리 및 프레임워크로는 React, Angular, Vue가 있다. 장점 간편한 운영 배...

[Vue] Angular 2 대신에 Vue.js를 선택한 이유

[Vue] Angular 2 대신에 Vue.js를 선택한 이유 들어가며 이 글은 Medium 의 "Why we moved from Angular 2 to Vue.js(and why we didn't choose React)" 글을 번역한 글입니다. 항상 이상적일 수만은 없는 실제 프로젝트 여건에서 신중하게 프레임워크를 고민하고 선정해 나가는 과정을 상세하게 기술한 글입니다. Angular 2로 구축되어 있는 프로젝트를 업그레이드 & 마이그레이션 하는 과정에서 프로젝트의 현 상황과 여건을 반영한 프레임워크 선정 기준을 세우고, Vue.js 프레임워크를 적용해 나가는 개인 경험담이 담겨져 있습니다. 급격하게 요동치는 프론트엔드 프레임워크 시대에, 프론트엔드 개발자로서 항상 어떤 프레임워크를 선정해야 할지 고민하는 데 인사이트를 제공하는 글이 되길 바랍니다. 본문 우리는 최근에 Rever 라는 사이트에 Vue.js로 개발한 웹 페이지를 오픈했습니다. 16주 동안 641 개의 커밋이라는 강도 높은 개발 과정을 지나고 나니, Vue.js 도입하기를 잘했다는 생각이 듭니다. 8 달 전에 우리는 Angular 2를 쓰고 있었습니다. 정확하게 말하자면 Angular 2 베타 9 버전이었죠. 외주가 Angular 2로 제작해놓은 웹 사이트가 있었는데, UX/UI부터 설계까지 한 번도 만족한 적이 없었습니다. 심지어 어느 부분에 대해서는 Angular 2 자체가 맘에 들지 않았어요. 경험담을 더 얘기하기 전에, Angular 2 베타 9와 Angular 2.0는 완전히 다른 제품이라고 말하고 싶습니다. 그렇기 때문에 문제가 있었죠. Beta 9부터 2.0.0까지 8 개의 Beta 버전이 있었습니다. RC 8 개와 2.0.0 버전, 그리고 업그레이드까지 합치면 총 17 개의 버전이 있었죠. 우리는 Beta 9에서 2.0.0으로 업그레이드를 시도했지만, 상당히 많은 부분들이 호환되지 않아 업그레이드 작업이 버거워졌습니다. ...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자... Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 팀 내 뛰어난 풀스택 개발자분들이 Angular.js, Python, MySQL 모두 작업 가능하시니 오셔서 함께 배우며 즐겁게 작업하시면 됩니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. 개발 업무: 레터플라이의 핵심 기능인 편지, 사진을 제작하는 레터에디터, 포토에디터 개발. 이 기능들은 "모바일 웹을 통한 출력제품 생산 자동화 기술"(특허 출원 준비중)로서 레터플라이에서 자체개발했습니다. 근무 지역: 광화문역 5번출구 바로 앞 근무 환경: 책임과 존중을 중요시하는 수평적인 분위기, 도전적이며 서로에게 배우는 문화 근무 시간: 10-19시, 출근시간 자유 지정. 급여: 연봉/스톡옵션 협의 지원 방법: 팀 지원하기 더 많은 내용은 더 많은 내용은 더팀스 에서 확인하세요! from http://theteams.tistory.com/721 by ccl(A) rewrite - 2020-03-20 09:20:18