18

I'd like to use Firebase to send push notifications to both Android and iOS devices which are localized.

I realized we didn't really have a solution for sending localized messages to subscribed topics. Pretend I have a message 'North Korea leader threatens Guam' that I want to send to people subscribed to the 'News' topic and 1000 people are subscribed (and they all speak different languages). I was hoping Firebase records the devices locale when requesting a FCM token, and that I could just send an array of messages per locale to this topic and let FCM/firebase handle, like so:

{
  "default_message": "North Korea leader threatens Guam",
  "en_US": "North Korea leader threatens Guam",
  "en_GB": "North Korea leader threatens Guam",
  "es_MX": "Líder de Corea del Norte amenaza a Guam",
  "fr_FR": "Le chef de la Corée du Nord menace Guam",
  "de_DE": "Nordkorea-Führer droht Guam"
}

I have seen some references to maybe using title_loc_key, body_loc_key but don't see a good example on how the request would look like. These 2 params also imply maybe they are just used as a translation lookup key that the app also has to store and lookup locally, and I can't send a brand new off-the-cuff localized message to people (since the translation would have to be stored in the app beforehand like 'april_newsletter_text')? Not sure how it works, just throwing some thoughts out there.

Note: I am using a php library to do send firebase push notifications (Laravel-FCM). I believe some devs in our team have also extended that library a bit to do some custom tasks so if there is a way to do it directly via GCM (gcm-http.googleapis.com/gcm/) instead of FCM, then I can add.

KENdi
  • 7,576
  • 2
  • 16
  • 31
armyofda12mnkeys
  • 3,214
  • 2
  • 32
  • 39
  • Note: This is the most I found on StackOverflow about this and it doesn't really address the general question in the title (think it answers more the question in the body about 'how to localize when app is in special state'): https://stackoverflow.com/questions/37907470/firebase-push-messages-localization – armyofda12mnkeys Aug 10 '17 at 15:20
  • 1
    You are correct, if you want to use title_loc_key and the other keys, you need to add your localized content in your app bundle. See [Localizing the Content of Your Remote Notifications](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW9). FCM doesn't allow out-of-the-box automatic push notification localization. – nathan Aug 10 '17 at 15:37
  • We know locale of user when they install the app n register user. So we localize translations for our messages in our CMS, and the mobile api (in the CMS) can look up the translation for the message you want to send this specific user and send it. We also use our own topics system (via linking to our topics table) vs FCM's Topics since we needed to combine many AND and ORs (FCM i heard can only do 2 operators). so if u want to send a message to a user in topics '(Continent=='NorthAmerica' || 'SouthAmerica' && project=='ProjectA' || B)', we find all users in that topic then send msg to them. – armyofda12mnkeys Mar 19 '18 at 14:10
  • 2
    disadvantage of above is 500 users == 500 FCM messages vs 1 FCM message to a FCM topic. since translations are different per user. Especially if we have messages that have variables in them like "Hello ${first_name}, Please click here to use the app today on ${todays_date}" (we also do variable substitution server-side in our mobile api in the CMS) – armyofda12mnkeys Mar 19 '18 at 14:13

2 Answers2

1

If you are using firebase you have code like this in your JS worker

let messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
# Here  the callback for web push notification

Typically you would show the message in this callback. The task is to localise it. So you may just send users the message about a new message. Fetch localised message and then show it to the user. On fetch you would get Accept-Language http header or you can send the user id. Here is my example from my project:

messaging.setBackgroundMessageHandler(function (payload) {

    let data = [];
    try {
        if (payload.data && payload.data.data) {
            data = JSON.parse(payload.data.data);
        }
    } catch (e) {
        Sentry.captureException(e);
    }
    let query = Object.keys(data).map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])).join('&');

    return fetch(self.location.origin + "/web-push/run.json?" + query)
        .then(function (response) {
            # ........................
            #.  Skipped working with https status codes code.
            # ........................
            return response.json();
        })
        .then(function (response) {
            #
            #  Here we have an localised response from the server
            # 
            if (response) {
                return self.registration.showNotification(response.title, {
                    priority: "high",
                    tag: 'renotify',
                    requireInteraction: true,
                    body: response.description,
                    icon: response.icon,
                    image: response.image,
                    url: response.link,
                    click_action: response.link,
                    data: {
                        url: response.link
                    },
                    vibrate: [500, 110, 500, 110, 450, 110, 200, 110, 170, 40, 450, 110, 200, 110, 170, 40, 500]
                })
            }
        })
        .catch(function (err) {
            Sentry.captureException(err);
        });
});
Andrew
  • 123
  • 1
  • 7
1

You can combine topics using "conditions" (see docs). These allow you to send your notification to a combination of topics, eg.

const message = {
    notification: {
        title: 'North Korea leader threatens Guam',
        body: '...'
    },
    condition: `'KoreaNews' in topics && 'LangEnGB' in topics`
};

const messageFr = {
    notification: {
        title: 'Le chef de la Corée du Nord menace Guam',
        body: '...'
    },
    condition: `'KoreaNews' in topics && 'LangFrFR' in topics`
};
icguy
  • 560
  • 4
  • 14