Ionic Push Notification - Android and iOS working

Really great i am looking for this only … i will try this and let u know the result … thanks

thx a freaking lot @ankushagg93 for the tutorials, really helpful, specially the iOS certificate part!

Never delete them, these are gold :slight_smile:

Your github code is working fine with firebase cloud messaging. Thank you for the code.

Hi All,

I updated github code and medium tutorials to latest ionic 2.0 stable. Also updated FCM screenshots to reflect current configurations :thumbsup:

-Thanks

3 Likes

This sends push to all users, as per Canadian Spam laws we have to make sure we have permission how do I implement .hasPermission() I cant get the timing to work.

Hi All,

I am using Ionic 3 with Ionic Native Push Notifications on the client and Java com.notnoop.apns on the server.

I can get the Push Notifications to work successfully on an Android devise. However, on an iOS devise, the client does not display the notification.

client (ts)

        let topics: string[] = [this.personModelLoggedIn.uid];
        const options: PushOptions = {
          android: {
            senderID: "893141127008",
            sound: "true",
            vibrate: "true",
            topics: topics
          },
          ios: {
            senderID: "893141127008",
            alert: "true",
            badge: true,
            sound: "true"//,
            //topics: topics
          },
          windows: {}
        };
        const pushObject: PushObject = this.push.init(options);


        pushObject.on('notification').subscribe((data: any) => {
          alert('Received Notification!!! message = ' + data.message);
        });

server (java)

Android

private String sendAndroidPushNotification(String device_token, String topics, String title, String message)
		throws Exception {
	String pushMessage = null;
	if (device_token != null && !device_token.equals("null")) {
		pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\":\""
				+ device_token + "\"}";
	} else {
		pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\": \"/topics/"
				+ topics + "\"}";
	}
	// Create connection to send FCM Message request.
	URL url = new URL("https://fcm.googleapis.com/fcm/send");
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
	conn.setRequestProperty("Content-Type", "application/json");
	conn.setRequestMethod("POST");
	conn.setDoOutput(true);
	// Send FCM message content.
	OutputStream outputStream = conn.getOutputStream();
	outputStream.write(pushMessage.getBytes());

	return "Android Push Notification: " + conn.getResponseCode() + " " + conn.getResponseMessage() + " - " + pushMessage;
}

iOS

private String sendIOSPushNotification(String device_token, String topics, String title, String message)
		throws Exception {
	ApnsService service = APNS.newService().withCert(PATH_TO_P12_CERT, CERT_PASSWORD).withSandboxDestination()
			.build();

	String payload = APNS.newPayload()
			// .customFields(map)
			.alertBody(title + " " + message).sound("default").build();

	//service.push(Utilities.encodeHex(topics.getBytes()), payload);
	service.push(Utilities.encodeHex(device_token.getBytes()), payload);
	return "iOS Push Notification: " + title + " " + message;
}

When the above two java methods get called with the appropriate devise tokens, the Android devise receives a notification, but the iOS devise does not.

If anyone can advise what’s wrong with my iOS code (either client or server), I would appreciate your advise.

Hi ankushagg93, please can you take a look at this?

Hey guys,

   I was trying to use push notification with steps you have mentioned.

   Once I open my app I am able to see Device registered alert. But when I try to send notification from Firebase I am unable to see any success or error message.

   Also I am getting device registered alert every time I open my app.

   Kindly help me out.

I’m having the same problem. How to get the device token? I’m running the app on my phone using “Ionic DevApp”.

What do you need to do to make notifications when the application is closed?

Is there any way to get the notification when the iOS app is on foreground?

The method on notification is not fired when the app is in foreground on iOS

Hi @ankushagg93

Let assume I have 5 devices. I want to send push notification to exact one device. How do I send to that exact device.

@newBeat Each device has its own registration_id (token). Just send the notification to the device with that token only. You need to pass the token to your back-end/database in order to retrieve it to send the notification.

I am receiving two different tokens while running the app on ios device one for android and one for ios.
but not able to get the ios token in the log. can anyone have a solution? Thanks in advance!

you mean add device registration_id instead of add SENDER_ID which is created from firebase app to here

<plugin name="phonegap-plugin-push" spec="1.10.5">    
  <variable name="SENDER_ID" value="YOUR_SENDER_ID"/>   
</plugin>

Is the below uuid that was mentioned by you as the registration_id

this.uniqueDeviceID.get()
  .then((uuid: any) => console.log(uuid))
  .catch((error: any) => console.log(error));

@newBeat No, that’s the device unique id related to your application. By registration_id I mean the token you receive when you subscribe to push notifications:


push.on('registration').subscribe(data => {
    console.log("device token ->", data.registrationId);
    //TODO - send device token to server
});

Then in your server (back-end) you send it to the device with that token. If it’s an Android device you can send it like:

{
    "registration_ids": [registrationId],
    "data": {
        "title": "My Title",
        "message": "My message!"
    }
}

For more info:

Note: The SENDER_ID (I’m assuming you are using FCM) is the your FCM Project Id (it is the same for all users of your app and is related to your FCM project). In the new versions of phonegap-plugin-push you don’t inform the SENDER_ID anymore, you use a file google-services.json. It is not related to the device token.

1 Like

@ManOnMission Your description is not very clear, please, clarify. From what I see in your log, the first should not be the device token, only the second (FCM Registration Id). Is that your android log and you don’t receive anything in iOS?

Try to put a logs right before the registration call and inside your subscription (both in success and error):

console.log('registration (before)');

push.on('registration').subscribe(
	data => console.log('registration data', data),
	error => console.error('registration error', error),
);

Thank you @lucasbasquerotto. You saved me this time. It works perectly.

OneSignal is a wonderful plugin.