Capacitor - Not receiving push notifications in Ionic + Angular app - android

I've started moving on capacitor. After reading https://capacitorjs.com/docs/cordova/known-incompatible-plugins I found that capacitor doesn't support some cordova plugins.
I'm using cordova-plugin-fcm-with-dependecy-updated for android and cordova-plugin-fcm for iOS in my app for push notifications but capacitor doesn’t support these plugins so I used capacitor native approach guided in https://capacitorjs.com/docs/apis/push-notifications#addlistener.
The native approach is not throwing any error and I am able to get registered token as well but I am not receiving push notifications on registered device.
I also tried https://www.npmjs.com/package/capacitor-fcm but fcm.getToken() is returning null.
capacitor.config.json
"plugins": {
"PushNotifications": {
"presentationOptions": [
"badge",
"sound",
"alert"
]
}
}
app.ts
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private fcmService: FcmService
) {
this.initializeApp();
}
ngOnInit() {}
initializeApp() {
this.platform.ready().then(() => {
setTimeout(() => {
this.splashScreen.hide();
}, 300);
this.fcmService.initPush();
});
}
}
fcm.service.ts
import { Injectable } from '#angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed,
Capacitor
} from '#capacitor/core';
import { Router } from '#angular/router';
const { PushNotifications, Modals } = Plugins;
import { FCM } from '#capacitor-community/fcm';
const fcm = new FCM();
const { FCMPlugin } = Plugins;
#Injectable({
providedIn: 'root'
})
export class FcmService {
constructor(
private router: Router) { }
initPush() {
alert('Capacitor platform' + Capacitor.platform);
if (Capacitor.platform !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermission().then((permission) => {
if (permission.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
alert('No permission for push granted');
}
});
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
alert('APN token: ' + JSON.stringify(token));
fcm.getToken().then((r) => {
alert(`FCM Token: ${r.token}`); //---- showing null.
}).catch((err) => {
alert(`FCM Token ERROR: ${JSON.stringify(err)}`);
});
}
);
PushNotifications.addListener('registrationError', (error: any) => {
alert('Registration Error: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
async (notification: PushNotification) => {
Modals.alert({
title: notification.title,
message: notification.body
})
}
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
async (notification: PushNotificationActionPerformed) => {
alert('Action performed: ' + JSON.stringify(notification.notification));
}
);
}
}
Is there anything I am missing or I need to add extra configurations to receive push notifications ?

You added SHA certificate fingerprints in your firebase project and update google service file ?

Related

Ionic 5 Capacitor: Push Notification register UserGroup to firebase server/console?

I made the push notifications according to the Capacitor instructions. Below is the code for this.
But how can I specify the device to a user group in firebase, so that a device is assigned to a user group and I can therefore choose between the user groups when placing a push notification?
How can this approach be used to assign a device to a user group in firebase?
import { Component, OnInit } from '#angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed } from '#capacitor/core';
const { PushNotifications } = Plugins;
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
ngOnInit() {
console.log('Initializing HomePage');
PushNotifications.register();
PushNotifications.addListener('registration',
(token: PushNotificationToken) => {
alert('Push registration success, token: ' + token.value);
}
);
PushNotifications.addListener('registrationError',
(error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
}
);
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotification) => {
alert('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
}
);
}

Google-Login with capacitor-oauth2/Plugins.OAuth2Client.authenticate () does not work on Android device

Initial Situation:
I need to implement a Google login with Ionic which works on a web platform as well as on an android device.
Therefore I use:
Ionic 5.2.2
Capacitor 1.1.1
Capacitor OAuth 2 client plugin 1.0.0
With that setup I achieved already:
Web-Login workes perfectly
Problem:
Login in from an Android device doesn't work
I followed the steps in the readme from https://github.com/moberwasserlechner/capacitor-oauth2/blob/master/README.md
I registered the plugin OAuth2Client in my app.component.ts
I implemented a method googleLogin() where I call Plugins.OAuth2Client.authenticate() with OAuth2AuthenticateOptions
app.component.ts
import { Component, OnInit } from '#angular/core';
import { registerWebPlugin } from "#capacitor/core";
import { OAuth2Client } from '#byteowls/capacitor-oauth2';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
console.log("Register custom capacitor plugins");
registerWebPlugin(OAuth2Client);
}
}
home.page.ts
import { Component } from '#angular/core';
import { Plugins } from '#capacitor/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor() { }
async googleLogin() {
try {
const resourceUrlResponse = await Plugins.OAuth2Client.authenticate({
appId: "XXX.apps.googleusercontent.com",
authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
scope: "email profile",
resourceUrl: "https://www.googleapis.com/userinfo/v2/me",
web: {
redirectUrl: "http://localhost:8100",
windowOptions: "height=600,left=0,top=0"
},
android: {
appId: "XXX.apps.googleusercontent.com",
responseType: "code",
customScheme: "com.xxx.playground.googleLogin07"
}
})
}
catch (err) {
console.error(err);
}
}
}
On an device this code results in an error-message from Google:
enter image description here
This is plausible. It seems to be that the method Plugins.OAuth2Client.authenticate() tries to do a web-based login where an android login is needed. Am I right?
If I make a call without the "web"-parameter like this...
const resourceUrlResponse = await Plugins.OAuth2Client.authenticate({
appId: "XXX.apps.googleusercontent.com",
authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
scope: "email profile",
resourceUrl: "https://www.googleapis.com/userinfo/v2/me",
android: {
appId: "XXX.apps.googleusercontent.com", //--> I tried both, android- and web-client key from the google clout platform console.
responseType: "code",
customScheme: "com.xxx.playground.googleLogin07"
}
})
...the method Plugins.OAuth2Client.authenticate() returns a blank error object --> {}
What am I doing wrong?

How to conditionally set root page in ionic 4?

I'm working on ionic 4 application. when the user signs In, I added a checkbox to asks for Remember me, so the next time the user open the app it doesn't show the login page and directly forward the user to Home page. I have google and found this. However, while using the accepted solution, I encountered an issue, which it shows the login page for 2 or 3 seconds, then open the Home page. How I can safely achieve it without delay?
app.component.ts
import { SmsVerificationService } from 'src/app/services/SMS/sms-verification.service';
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 { FCM } from '#ionic-native/fcm/ngx';
import { Plugins, Capacitor } from '#capacitor/core';
import { Router } from '#angular/router';
import { Storage } from '#ionic/storage';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private fcm: FCM,
private route: Router,
private storage: Storage
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.fcm.getToken().then(token => {
console.log(' token is ', token);
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log('on token refresh ', token);
});
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]);
}
});
this.storage.get('isLogined').then(data => {
if (data)
this.route.navigateByUrl('/main-tab');
})
this.statusBar.styleDefault();
this.splashScreen.hide();
if (Capacitor.isPluginAvailable('SplashScreen')) {
Plugins.SplashScreen.hide();
}
});
}
}
The codes that are supposed to change the page
this.storage.get('isLogined').then(data => {
if (data)
this.route.navigateByUrl('/main-tab');
})
Do you have a separate login component? If so, you can create and add a guard to your login component to navigate to your main page when Remember me was checked.

Transparent status bar ionic2

I need transparent status bar ionic 2.
I installed npm install --save #ionic-native/status-bar.and also
refer this link https://ionicframework.com/docs/v2/native/status-bar/
I used this.statusBar.backgroundColorByHexString("#0e5591"); But It's not working.
Below my app component.
import { Component, ViewChild,Inject } from '#angular/core';
import { Nav,NavController,Platform ,AlertController,MenuController,App,IonicApp} from 'ionic-angular';
import { Splashscreen ,Network,Toast} from 'ionic-native';
import { StatusBar } from '#ionic-native/status-bar';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
public app: App;
currentuser;
#ViewChild(Nav) nav1: Nav;
auth:any;
menu;
nav:NavController;
constructor(private statusBar: StatusBar,public appCtrl: App,public menu1: MenuController,public alertCtrl:AlertController,public platform: Platform,public authservice:Authservice) {
this.auth=localStorage.getItem("email");
console.log("Auth"+this.auth);
// this.rootPage = this.isUserLoggedIn ? LoginPage : MycomplaintsPage;
// console.log(this.rootPage);
if(this.auth != undefined && this.auth != null)
{
this.rootPage = DashboardPage;
}
this.showRoot = true;
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.statusBar.backgroundColorByHexString("#0e5591");
Splashscreen.hide();
if(Network.type === Connection.NONE)
{
console.log("success");
let alert = this.alertCtrl.create({
title: "Internet Connection",
subTitle:"Please Check Your Network connection",
buttons: [
{
text: 'Ok',
handler: () => {
this.platform.exitApp();
}
}
]
});
alert.present();
}
});
}
exit(){
let alert = this.alertCtrl.create({
title: 'Confirm',
message: 'Do you want to exit?',
buttons: [{
text: "exit?",
handler: () => { this.exitApp() }
}, {
text: "Cancel",
role: 'cancel'
}]
})
alert.present();
}
exitApp(){
this.platform.exitApp();
}
}
I am getting this err
ORIGINAL EXCEPTION: No provider for StatusBar!
Kindly advice me,
Thanks
It looks like you have two versions of ionic native from your imports.
import { Splashscreen ,Network,Toast} from 'ionic-native';
import { StatusBar } from '#ionic-native/status-bar';
Make sure you only have #ionic-native/core in your package.json.
Also according to the latest ionic-native docs,
you need to set the plugin as provider in ngModule:
#NgModule({
...
providers: [
...
Statusbar
...
]
...
})

ionic2 login through facebook not working

as i was trying to log into my app using facebook on ionic2 but when i used that code it is showing error that " Cannot find name 'facebookConnectPlugin'." as i have already installed cordova plugin
login() {
facebookConnectPlugin.login(['email'], function(response) {
alert('Logged in');
alert(JSON.stringify(response.authResponse));
}, function(error){
alert(error);
})
}
getdetails() {
facebookConnectPlugin.getLoginStatus((response) => {
if(response.status == "connected") {
facebookConnectPlugin.api('/' + response.authResponse.userID + '?fields=id,name,gender',[],
function onSuccess(result) {
alert(JSON.stringify(result));
},
function onError(error) {
alert(error);
}
);
}
else {
alert('Not logged in');
}
})
}
logout() {
facebookConnectPlugin.logout((response) => {
alert(JSON.stringify(response));
})
}
then i found another solution which is
fblogin(){
this.platform.ready().then(() => {
Facebook.login(["email"]).then((result) => {
console.log(result)
})
})
}
it is also showing an error that : "Property 'platform' does not exist on type 'HomePage'."
i am running that code using "ionic run android" and my device is connected and other application running normally.
Check the docs.
Do
import {Platform} from 'ionic-angular`;
Also declare cordova plugins globally immediately after import statements and before the class is defined.
//import statements.
declare var facebookConnectPlugin:any;
#Component()
//...

Categories

Resources