Ionic 3 Установить разрешение уведомлений на кнопке переключения - PullRequest
0 голосов
/ 01 июля 2019

Мне нужно знать, как я могу использовать разрешение уведомлений в ионном приложении на кнопке переключения.Я хочу, чтобы пользователь отключил тумблер, чтобы пользователь не мог получить уведомление FCM Push, если тумблер включен, тогда пользователь может получить уведомление.Я пытаюсь использовать локальное хранилище, когда пользователь отключает переключатель. Я устанавливаю переключатель false в localalstoreage, поэтому, когда пользователь снова открывает приложение, кнопка переключения отключается.

  <ion-item>
    <ion-toggle [(ngModel)]="isToggled" (ionChange)="notify()" item-start checked="true" ></ion-toggle>
        <ion-label item-end style="text-align: right;">تلقي الاشعارات
</ion-label>
  </ion-item>

.ts

  constructor(private nativeStorage: NativeStorage, private push: Push, public platform: Platform, private fcm: FCM,  public statusBar: StatusBar, public splashScreen: SplashScreen) {


    this.initializeApp();

  }

  initializeApp() {
       this.platform.ready().then(() => {
       this.check();

      //Notifications
      if(this.isToggled == true){
      this.fcm.subscribeToTopic('all');
      this.fcm.getToken().then(token=>{
          console.log(token);
      })
      this.fcm.onNotification().subscribe(data=>{

        if(data.wasTapped){
                this.nav.setRoot(ArticledetailsPage, {x:data.newsid});

          console.log("Received in background");
        } else {
          console.log("Received in foreground");
        };
      })
      if(this.isToggled == true){
        this.fcm.subscribeToTopic('marketing');
      }

      else{
      this.fcm.unsubscribeFromTopic('marketing');
      }

      //end notifications.

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.splashScreen.hide();
    });
  }



        notification(){
  this.nav.push(NotificationPage);
  }

public notify() {
  console.log("Toggled: "+ this.isToggled); 
  this.nativeStorage.setItem('toggle', {property: this.isToggled, anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Stored item!'),
    error => console.error('Error storing item', error)
  );

}

check(){
  this.nativeStorage.getItem('toggle')
  .then(
    (data) => {
    console.log(data.property),
    this.isToggled = data.property;
    console.log(this.isToggled);
    }
  );
}
}

Ответы [ 3 ]

2 голосов
/ 14 июля 2019

Это просто в вашей функции notify (), вы получаете значение переключаемого пользователя, равное false или true, когда приложение открыто, если значение переключателя равно true, тогда this.fcm.subscribeToTopic('all');. и если это неверно, просто отмените подписку. Надеюсь, что это ваш идеальный ответ

initializeApp() {
    this.platform.ready().then(() => {
      this.check();

      //Notifications
      this.fcm.getToken().then(token => {
        console.log(token);
      })
      this.fcm.onNotification().subscribe(data => {

        if (data.wasTapped) {
          this.nav.setRoot(ArticledetailsPage, { x: data.newsid });

          console.log("Received in background");
        } else {
          console.log("Received in foreground");
        };
      })


      //end notifications.

      if (this.isToggled == true) {
        this.fcm.subscribeToTopic('all');
      }

      else {
        this.fcm.unsubscribeFromTopic('all');
      }

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.splashScreen.hide();
    });
  }



  notification() {
    this.nav.push(NotificationPage);
  }

  public notify() {
    console.log("Toggled: " + this.isToggled);
    this.nativeStorage.setItem('toggle', { property: this.isToggled, anotherProperty: 'anotherValue' })
      .then(
        () => console.log('Stored item!'),
        error => console.error('Error storing item', error)
      );
    if (this.isToggled == true) {
      this.fcm.unsubscribeFromTopic('all');
    }
    else {
      this.fcm.unsubscribeFromTopic('all');
    }
  }

  check() {
    this.nativeStorage.getItem('toggle')
      .then(
        (data) => {
          console.log(data.property),
            this.isToggled = data.property;
          console.log(this.isToggled);
        }
      );
  }
0 голосов
/ 14 июля 2019

1) создать службу

notification service.ts
====================
appConfig = {
 pushNotificationStatus : true    // false

}

2) Выполнить вызов службы для включения / отключения pushNotificationStatus на кнопке переключения и обновить значение в notification service.ts appconfig как: -

// suppose putservice call for enable/disable push notification

constructor(public notifServ: NotificationService){}
ontoggle(){
 this.https.post(url,{}).subscribe(res =>{
  this.notifServ.appConfig.pushNotificationStatus = true // false based on service call
})
}

3) app.component.ts or component load, проверка pushNotification включена или отключена для приложения в каком-либо вызове (может быть вызовом профиля или любым вызовом, который отправляет статус pushNotification пользователя для приложения) a) сделать вызов и обновить значениев

this.notifServ.appConfig.pushNotificationStatus = true // false

Или

Выполнение этого в localStorage не лучший способ, но его можно выполнить, если вы хотите обработать его на уровне клиента: -

For this, whenever your component loads `clear localStorage` or set `push notiifcation key` in localStorage as empty or null or may delete.

Примечание: вышеуказанный первый метод, т.е. service also works at client level, just update the appConfig in service and use it as refrence when do enable/disable push notifications.

0 голосов
/ 12 июля 2019

Правильным способом является запись серверной функции для регистрации незарегистрированного уведомления

Eg : /myapi/stopPushnotification

Это тот, который удаляет / добавляет токен из нашей базы данных или отслеживает его в другой таблице. В приложении у нас есть переключатель, который включает и выключает его. это лучший способ сделать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...