Dave Long
Dave Long

Reputation: 9759

Handling Push Notifications when app is open in Ionic 2

In Ionic 2, I'm trying to handle an event when the user is currently in the application so that I can pop an alert message and navigate to a different view. In my App constructor, I have the following code:

export class MyApp {
  private rootPage: any;

  constructor(private platform: Platform, private app: App, private push: Push) {
    if (UserService.isLoggedIn()) { this.rootPage = PickupPage; }
    else { this.rootPage = LoginPage; }

    console.log('We are here! We are here! We are here!');
    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.
      console.log('Registering notifications handler');
      this.push.rx.notification().subscribe(msg => {
        alert(msg.title);
        console.log('Got something!');
        console.dir(msg);
      });
      StatusBar.styleDefault();
    });
  }
}

When I send a notification, on Android I get the notification coming up in the pull down bar on Android, but no console or alert inside the app and on iOS I just get nothing. No console message or alert and no notification in the notification center.

§ ionic -v
2.0.0-beta.37

Upvotes: 0

Views: 1361

Answers (1)

Dave Long
Dave Long

Reputation: 9759

It looks like I had to add the senderID in CloudSettings at push.pluginConfig.android.senderID to work, like follows:

const cloudSettings: CloudSettings = {
  'core': { 'app_id': '***' },
  'push': {
    'sender_id': '***',
    'pluginConfig': {
      'ios': { 'badge': true, 'sound': true },
      'android': { 'senderID': '***', 'iconColor': '#d1b561' }
    }
  }
}

Not sure if that is 100% the answer as it seems like the CloudSettings object doesn't like to be changed after the app is installed.

Edit

It seems like I've gotten things working a bit further. According to the documentation, you should make a call to this.push.register() everytime the app opens. I found that by updated my App's constructor in app.ts to the following, push notifications appear much more stable:

platform.ready().then(() => {
  // Register to receive push notifications
  this.push.register().then((token: PushToken) => {
    // Send the token to Ionic cloud so we can send to it through the API
    return this.push.saveToken(token)
  });
  // Setup our handler so we can perform actions on push notifications
  this.push.rx.notification().subscribe(msg => {
    console.log(`Received ${msg.title}: ${msg.message}`);
    if (msg.app.asleep || msg.app.closed) {
      // The app is being opened from a notification
    } else {
      // The app was already open when the notification was received
    }
  });
  ...
});

Upvotes: 0

Related Questions