Skip to content

Instantly share code, notes, and snippets.

@Kaoschuks
Created March 13, 2021 18:24
Show Gist options
  • Save Kaoschuks/17581d411a3fea5ddaad2d6619745250 to your computer and use it in GitHub Desktop.
Save Kaoschuks/17581d411a3fea5ddaad2d6619745250 to your computer and use it in GitHub Desktop.
Ionic capacitor push notification using capacitor plugin and angular fire
import { Component } from '@angular/core';
import { FcmProvider } from './providers/core/fcm';
import { GlobalsProvider } from './providers/core/globals';
import { environment } from 'src/environments/environment.prod';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements AfterViewInit {
constructor(
private fcm: FcmProvider,
private _deeplinkservice: DeeplinkService,
public globals: GlobalsProvider,
) {
this.initializeApp();
}
private initializeApp() {
this.globals.platform.ready()
.then(() => {
this.pushNotification();
}).catch((err: any) => {
console.log("App platform running error", err)
})
}
private pushNotification() {
try {
this.fcm.ngOnInit();
this.fcm.getPushNotification()
.then((data:any) => {
// alert(data)
this.globals.showLocalNotification({
schedule: {at: new Date(new Date().getTime())},
title: data.title,
body: data.message,
id: 1
});
}).catch((ex: any) => {
throw ex
})
} catch (ex) {
console.error('Error with Push plugin ' + JSON.stringify(ex));
}
}
}
import { Injectable, OnInit } from '@angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed } from '@capacitor/core';
import { GlobalsProvider } from './globals';
import { environment } from 'src/environments/environment.prod';
import { AngularFireMessaging } from '@angular/fire/messaging';
declare var $: any;
const { PushNotifications } = Plugins;
@Injectable({
providedIn: 'root'
})
export class FcmProvider implements OnInit
{
devices: Array<any> = [];
constructor(
private firemsg: AngularFireMessaging,
private globals: GlobalsProvider,
){
}
async ngOnInit() {
let result: any;
if(this.globals.platform.is('capacitor')) {
result = await PushNotifications.requestPermission();
} else {
this.firemsg.requestPermission.subscribe((res: any) => {
console.log(res);
})
}
if (result && result['granted']) {
PushNotifications.register();
const token: any = await this.getToken();
const response: any = await this.saveToken(token);
console.log(response);
} else {
console.log("Push notification error on register", result);
}
}
async saveToken(token: string) {
return await new Promise((resolve, reject) => {
// alert(token);
resolve(token);
})
}
subscribeToChannel(name: string) {
}
unsubscribeFromChannel(name: string) {
}
private async getToken() {
return await new Promise((resolve, reject) => {
try {
// On success, we should be able to receive notifications
if(this.globals.platform.is('capacitor')) {
PushNotifications.addListener('registration',
(token: PushNotificationToken) => {
resolve(token.value);
}
);
} else {
this.firemsg.getToken.subscribe((token: any) => {
console.log(token);
resolve(token);
})
}
}catch(ex) {
reject(ex);
}
})
}
async sendingPushNotification(fcm: string, title: string, msg: any, extra: any = null, page: any) {
return await new Promise((resolve, reject) => {
page = encodeURI(`${environment.deeplink_url}${page}`);
$.ajax({
type : 'POST',
url : "https://fcm.googleapis.com/fcm/send",
headers : {
Authorization : 'key=' + 'AAAAGnd2Nsg:APA91bFQyaAEa6SsDycc8UyJ5h1UVbcyDLcZ4pv3M40XryofpQC3d7Y1vLhKBIwyevk7ashZbZIWAQJWArvVF8sfNRXD4rqAI0ABVSwsufa7oIzsCVFPJAidEOs8KFSg_6DQy4uBqgeh'
},
contentType : 'application/json',
dataType: 'json',
data: JSON.stringify(
{
"to": fcm,
"notification": {
"title": title,
"extra": extra,
"click_action": page,
"body": msg
}
}
),
success : function(response) {
if(response.success == 1){
resolve(response);
} else {
reject(response);
}
},
error : function(xhr, status, error) {
reject(xhr.error);
}
});
})
}
async getPushNotification() {
return await new Promise((resolve, reject) => {
try {
if(this.globals.platform.is('capacitor')) {
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotification) => {
resolve(notification);
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
resolve(notification);
}
);
} else {
// web push
this.firemsg.messages.subscribe(
(payload) => {
console.log(payload);
resolve(payload);
})
}
} catch(ex) {
if(this.globals.platform.is('capacitor')) {
PushNotifications.addListener('registrationError',
(error: any) => {
reject('Error on registration: ' + JSON.stringify(error));
}
);
} else {
reject('Error on registration: ' + JSON.stringify(ex));
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment