Home > Software design >  Push notifications not work in IOS IONIC 4 cordova
Push notifications not work in IOS IONIC 4 cordova

Time:06-15

I’m using Ionic 4 and ANGULAR version 9 trying to send notification in IOS using Cordova.

I did all the requirements to push IOS notification and it was working fine before that but I’m not sure what happened if some packages version not match or whatever.

Here is my package.json

{
  "name": "tagy",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "~9.1.6",
    "@angular/core": "~9.1.6",
    "@angular/forms": "~9.1.6",
    "@angular/platform-browser": "^9.1.13",
    "@angular/platform-browser-dynamic": "~9.1.6",
    "@angular/router": "~9.1.6",
    "@ionic-native/android-permissions": "^5.29.0",
    "@ionic-native/app-rate": "^5.28.0",
    "@ionic-native/app-version": "^5.30.0",
    "@ionic-native/background-fetch": "^5.36.0",
    "@ionic-native/background-mode": "^5.36.0",
    "@ionic-native/badge": "^5.36.0",
    "@ionic-native/barcode-scanner": "^5.30.0",
    "@ionic-native/camera": "^5.27.0",
    "@ionic-native/core": "^5.0.7",
    "@ionic-native/fcm": "^5.31.1",
    "@ionic-native/file-transfer": "^5.33.0",
    "@ionic-native/geolocation": "^5.29.0",
    "@ionic-native/location-accuracy": "^5.29.0",
    "@ionic-native/native-geocoder": "^5.29.0",
    "@ionic-native/onesignal": "^5.36.0",
    "@ionic-native/photo-viewer": "^5.32.1",
    "@ionic-native/push": "^5.36.0",
    "@ionic-native/social-sharing": "^5.28.0",
    "@ionic-native/splash-screen": "^5.0.0",
    "@ionic-native/status-bar": "^5.0.0",
    "@ionic/angular": "^5.0.0",
    "chart.js": "^2.9.4",
    "com-sarriaroman-photoviewer": "1.2.5",
    "cordova-android": "7.1.4",
    "cordova-browser": "5.0.4",
    "cordova-ios": "6.1.0",
    "cordova-plugin-add-swift-support": "^2.0.2",
    "cordova-plugin-android-permissions": "^1.1.0",
    "cordova-plugin-androidx": "^3.0.0",
    "cordova-plugin-androidx-adapter": "^1.1.1",
    "cordova-plugin-app-version": "^0.1.9",
    "cordova-plugin-apprate": "^1.5.0",
    "cordova-plugin-background-mode": "0.7.3",
    "cordova-plugin-badge": "0.8.8",
    "cordova-plugin-camera": "^4.1.0",
    "cordova-plugin-device": "2.0.2",
    "cordova-plugin-dialogs": "^2.0.2",
    "cordova-plugin-fcm-with-dependecy-updated": "2.2.5",
    "cordova-plugin-file": "6.0.2",
    "cordova-plugin-file-transfer": "1.7.1",
    "cordova-plugin-firebase": "2.0.5",
    "cordova-plugin-geolocation": "^4.0.2",
    "cordova-plugin-ionic-keyboard": "^2.0.5",
    "cordova-plugin-ionic-webview": "^4.0.0",
    "cordova-plugin-nativegeocoder": "^3.4.1",
    "cordova-plugin-nativestorage": "^2.3.2",
    "cordova-plugin-request-location-accuracy": "^2.3.0",
    "cordova-plugin-splashscreen": "5.0.2",
    "cordova-plugin-statusbar": "2.4.2",
    "cordova-plugin-whitelist": "1.3.3",
    "cordova-plugin-x-socialsharing": "^6.0.2",
    "cordova-support-google-services": "1.3.2",
    "es6-promise-plugin": "^4.2.2",
    "ionic-selectable": "^4.7.1",
    "ngx-qrcode2": "^9.0.0",
    "npm": "^7.21.1",
    "phonegap-plugin-barcodescanner": "^8.1.0",
    "phonegap-plugin-multidex": "1.0.0",
    "phonegap-plugin-push": "2.3.0",
    "rxjs": "^6.5.5",
    "rxjs-compat": "^6.6.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.901.5",
    "@angular/cli": "9.1.15",
    "@angular/compiler": "~9.1.6",
    "@angular/compiler-cli": "~9.1.6",
    "@angular/language-service": "~9.1.6",
    "@ionic/angular-toolkit": "^2.1.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-ionic-keyboard": "^2.2.0",
    "cordova-plugin-ionic-webview": "^4.2.1",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-statusbar": "^2.4.2",
    "cordova-plugin-whitelist": "^1.3.3",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~5.0.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~3.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~3.8.3"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-whitelist": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-ionic-webview": {
        "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27. "
      },
      "cordova-plugin-ionic-keyboard": {},
      "cordova-plugin-camera": {
        "ANDROID_SUPPORT_V4_VERSION": "27. "
      },
      "cordova-plugin-x-socialsharing": {},
      "cordova-plugin-androidx": {},
      "cordova-plugin-androidx-adapter": {},
      "cordova-plugin-apprate": {},
      "cordova-plugin-geolocation": {},
      "cordova-plugin-nativegeocoder": {},
      "cordova-plugin-android-permissions": {},
      "cordova-plugin-request-location-accuracy": {
        "PLAY_SERVICES_LOCATION_VERSION": "16. "
      },
      "cordova-plugin-app-version": {},
      "phonegap-plugin-barcodescanner": {
        "ANDROID_SUPPORT_V4_VERSION": "27. "
      },
      "cordova-plugin-file-transfer": {},
      "cordova-plugin-fcm-with-dependecy-updated": {},
      "com-sarriaroman-photoviewer": {},
      "cordova-plugin-background-mode": {},
      "cordova-plugin-badge": {}
    },
    "platforms": [
      "ios",
      "browser"
    ]
  }
}

Here is app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

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

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    FCM,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}

Here is app.component.ts code

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Platform, NavController, ToastController, AlertController, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { ProvidersService } from './providers.service';
import { FCM } from '@ionic-native/fcm/ngx';
import { SocialSharing } from '@ionic-native/social-sharing/ngx';
import { Badge } from '@ionic-native/badge/ngx';
import { Push, PushObject, PushOptions } from '@ionic-native/push/ngx';
import { BackgroundMode } from '@ionic-native/background-mode/ngx';

declare var Puship;

/*
interface Window {
    FirebasePlugin: any;
}*/

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
     public selectedIndex = 0;
  public appPages = [
    {
      title: 'Home',
      url: '/tabs',
      icon: 'home'
    },

    /*
    {
      title: 'Loyalty Points',
     // url: '/point',
      icon: 'ribbon'
    },

    */

     {
      title: 'Appointment',
      url: '/tabs/tab1/appointment',
      icon: 'ribbon'
    },



    {
      title: 'Loyalty e-Voucher',
      url: '/tabs/tab1/voucher',
      icon: 'cash'
    },


    {
      title: 'My Favorites Merchants',
      url: '/tabs/tab1/favourite',
      icon: 'heart'
    },
    {
      title: 'My Vehicle',
      url: '/update-vehicle',
      icon: 'cog'
    },
    {
      title: 'Profile & Settings',
      url: '/update-profile',
      icon: 'settings'
    },
    {
      title: 'Gallery',
      url: '/gallery',
      icon: 'image'
    },
    {
      title: 'Qr code',
      url: '/tabs/tab1/qrcode',
      icon: 'apps'
    },
    {
      title: 'Invite Friends',
      url: '/tabs',
      icon: 'people-circle',
      fn: () => this.share()
    },
    {
      title: 'About App',
      url: '/about',
      icon: 'information-circle'
    },
    {
      title: 'Help',
      url: '/help',
      icon: 'help-buoy'
    },
    {
      title: 'Deactivate Account',
      url: '/delete',
      icon: 'person-circle',
     fn: () => this.cancel()
    }
  ];
  pic:any;
  name:any;
  phone:any;
  code:any;
  data:any;
  items:any;
  data1:any;
  data2:any;
  auth2:any;
  items1:any;
  data3: any;
  items3: any;
  exist3: any;
  notiunread:any;
  point:any;
  userData={
        "token":"",
        "id":"",
        "plid":""
  };

  constructor(
      private router: Router,
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
      private providersservices: ProvidersService ,
      private toastctrl: ToastController,
      public navctrl: NavController,
      private menuCtrl: MenuController,
      private alertCtrl: AlertController,
      private socialSharing: SocialSharing,
    private badge: Badge,
    private backgroundMode: BackgroundMode,
    private fcm: FCM,
    private push: Push
  )


    
  {
    this.backgroundMode.enable();
    this.badge.set(this.notiunread);

    this.initializeApp();
  }

  


  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleBlackTranslucent();
      this.splashScreen.hide();
const SigninData = JSON.parse(localStorage.getItem("signindata"));
        if(SigninData!=null){
            console.log("have data");
            this.router.navigate(["/tabs"], { skipLocationChange: true });
        } else {
            console.log("no data");
            this.router.navigate(["/landing"], { skipLocationChange: true });
        }



    //  this.fcm.subscribeToTopic('marketing');
      this.fcm.getToken().then(token => {
        console.log(token);
      }, (err) => {
            console.log(err);
        });

      // ionic push notification example
      this.fcm.onNotification().subscribe(data => {
        console.log(data);
        if (data.wasTapped) {
          console.log('Received in background');
          this.router.navigate(['/tabs/tab1/notification']);
        } else {
          this.backgroundMode.enable();
          this.badge.set(this.notiunread);
          console.log('Received in foreground');
          this.call(data);
        }
      });

      // refresh the FCM token
      this.fcm.onTokenRefresh().subscribe(token => {
        console.log(token);
      }, (err) => {
            console.log(err);
        });



    });

    this.providersservices.getObservable().subscribe((data) => {
        console.log('Data received', data);
        this.pic = data.pic;
        this.name = data.name;
        this.phone = data.number;
    });

    const SigninData = JSON.parse(localStorage.getItem("signindata"));
    if(SigninData!=null){
        const SigninData = JSON.parse(localStorage.getItem("signindata"));
        this.userData.id=SigninData.mem_id;
        this.userData.token=SigninData.token;
        this.userData.plid = "7";
        this.providersservices.postData(this.userData, "memberencrypt").subscribe((result) =>{
            this.data = result;
            this.items = this.data.data;
            this.code = this.items.mem_id;
            console.log(result);
        }, (err) => {
            console.log(JSON.stringify(err));
        });
    }


 this.providersservices.postData(this.userData, "badgenotification").subscribe((result) =>{
    this.data3 = result;
    this.items3 = this.data3.data;
    this.notiunread = this.items3.length;
    this.backgroundMode.enable();
      console.log(this.notiunread);
    this.badge.set(this.notiunread);

    if(Array.isArray(this.items3))
      this.exist3 = this.items3[0].exist;
    else
      this.exist3 = this.items3.exist;
    console.log(result);
  }, (err) => {
    console.log(JSON.stringify(err));
  });


    this.providersservices.postData(this.userData, "pointshare").subscribe((result) =>{
        this.data1 = result;
        this.items1 = this.data1.data;
        this.point = this.items1.pl_value;
        console.log(result);
    }, (err) => {
        console.log(JSON.stringify(err));
    });

    if(this.pic==undefined&&this.name==undefined&&this.name==undefined){
        const SigninData = JSON.parse(localStorage.getItem("signindata"));
        if(SigninData!=null){
            this.pic = SigninData.mem_photo;
            this.name = SigninData.mem_name;
            this.phone = SigninData.mem_phonetcode   SigninData.mem_phone;
        }
    }
    this.menuCtrl.enable(false, 'custom');



{
    //this.translate.addLangs(['en', 'ml']);
    //this.translate.setDefaultLang('en');
 }

  }


    switchLang(lang: string)
  {
  //  this.translate.use(lang);
  }

  async call(id:any){
        const alert = await this.alertCtrl.create({
          subHeader: id.title,
          message: id.body,
          buttons: [
            {
              text: "Open Notification",
              handler: () => {
                 this.router.navigate(['/notification']);
              }
            },
            {
              text: "Later",
              role: 'cancel',
              handler: () => {
                console.log('Cancel clicked');
              }
            }
          ]
        });
        await alert.present();
    }

    updateprofile(){
        this.router.navigate(['/update-profile']);
    }


    logout(){

        const RememberData = JSON.parse(localStorage.getItem("rememberme"));

        if(RememberData!=null){
          if(RememberData.rmbme=="false"){
            console.log("rmbme false");
            localStorage.removeItem("signindata");
            this.menuCtrl.enable(false, 'custom');
            this.navctrl.navigateRoot(['/login']);
          }else{
            localStorage.removeItem("signindata");
            this.menuCtrl.enable(false, 'custom');
            this.navctrl.navigateRoot(['/login']);
          }
          console.log("rmbme true");
        } else {
            console.log("null");
            localStorage.removeItem("signindata");
            this.menuCtrl.enable(false, 'custom');
            this.navctrl.navigateRoot(['/login']);
        }

        this.presentToast("Logout Successfully");
    }

    async share() {
      const alert = await this.alertCtrl.create({
           subHeader: 'Invite Friends',
            buttons: [
              {
                text: 'ANDROID',
                handler: () => {
                  this.shareandroid();
                }
              }, {
                text: 'IOS',
                handler: () => {
                 this.shareios();
                }
              }
            ]
        });
        await alert.present();
    }



    shareandroid() {
        this.socialSharing.share("").then(() => {
          console.log("Share: Success");
        }).catch(() => {

          console.error("Share: failed");
        });
    }

    shareios() {

         alert("In Progress");
    }

    async presentToast(a){
        const toast = await this.toastctrl.create({
            message: a,
            duration: 1500
        });
        toast.present();
    }


    async cancel(){

       const alert = await this.alertCtrl.create({
          header: 'Deactivate Account',
          message: 'Cancel will delete your account. Continue?',
           buttons: [
            {
              text: "Cancel",
              role: 'cancel',
              handler: () => {
                console.log('Cancel clicked');
              }
            }, {
              text: "Yes",
              handler: () => {
               this.providersservices.postData(this.userData, "deleteaccount").subscribe((result) => {
                    this.data2 = result;
                    this.auth2 = this.data2.result;
                    console.log(result);
                    console.log(this.auth2);

                    if(this.auth2.auth=="success"){
                        this.router.navigate(['/login']);

                    }
                }, (err) => {
                    this.presentToast("Please connect your device to internet!");
                });
              }
            }
          ]
        });

        await alert.present();
    }

    
}


I’m using the same code with android, the notification badge working fine. Could anyone help me check please? Thank you very much.

CodePudding user response:

You have to grant permission before getToken(). The permission at Android is by default, but iOS - don`t. For example:

try {
 const hasPermission = await this.firebase.hasPermission();
 if (!hasPermission) { permission = await this.firebase.grantPermission(); }
} catch (e) { console.log('FCM get permission error: ', e); }

CodePudding user response:

I have done solved this issue by upgrade xcode to version 13.4. The problem was because I was using old version of xcode.

  • Related