How to implement push notifications?

Hi guys, I am using Ionic Vue with Capacitor. I am trying to implement the “push notifications” part. My code below:

const push = Plugins.PushNotifications;
        push.register();
        push.requestPermission().then((answer) => {
            if (answer.granted) {
                push.createChannel({
                    id: 'relay',
                    name: 'relay',
                    description: '',
                    sound: '',
                    importance: 1,
                    visibility: 1,
                    lights: true,
                    lightColor: "green",
                    vibration: true,
                });

                push.addListener('pushNotificationReceived', notification => {
                    console.log(notification);
                });
            }
        });

The only part that I do not understand is, how can I push a notification to the phone now? I do not want to use a 3rd party tool of some kind. Can anyone please explain to me how I can push a message to the phone?

Push is not a solution you can handle without some sort of access to external APIs.

For that you would have to make some sort of system around local notifications, but they have to be scheduled when app is active, and i would guess that is not what you are after.

The system that makes you able to “Push” the notification to the phone when app is not active is built in to the phones operating system, and you have to communicate with Apple and/or Google.

Also Huawei has there own system since they are not allowed to use Google Services, but I have no experience with sending push to there services.

I think the easiest way to get started is with firebase for both iOS and Android.
There is a good tutorial for it in the documentation:

You could probably communicate directly with Apple services, but if you have to support iOS and Android, you still have to use firebase for Android, so why not use it for both platforms.

For testing on iOS in Simulator (xCode) you could use this method:

For the real thing you have to register your apps in a firebase project.
For iOS you have to create a certificate or Key in the Apple Developer portal, and use this in the registration in firebase console.
When you have registered apps in firebase you can use the firebase console GUI or API to send push messages to devices (by some filter or by sending array of pushTokens).

For targeting unique devices you have to use the pushToken the device gets when registering. This should be saved to your backend together with other info about user / device.

PushNotifications.addListener('registration', (token: PushNotificationToken) => {
    alert('Push registration success, token: ' + token.value); // Save this to backend
  },
);
2 Likes

Ah, now I understand it… thank you so much for your reply torgnywalin! I will make sure to look into this!