Sending an Image in Firebase Push Notifications

Viewed 229

I want to be able to display a mini image on the Push Notifications sent from Firebase. The problem that I'm having is that I use a single payload and sometimes the parameter in Image can be null (when no image is sent), I was reading this article: Send an image in the notification payload

But always got an error on my Console like this:

export const sendChatNotification = functions.firestore.document('chatrooms/{chatroomId}/chats/{chatId}').onCreate(async (snap, ctx) => {

    //In Comment OLD Way to get info data for the notification
    const token = snap.get('sendToDeviceToken'); //snap.data().sendToDeviceToken;
    const sender = snap.get('fullSenderName'); //snap.data().fullSenderName;
    const body = snap.get('message'); //snap.data().message;
    //const platform = snap.get('sendToDevicePlatform');

    var tokens  = [];

    tokens.push(token);

    console.log('Tokens: ' + tokens);

    var imageInfo = body.substring(0, 38);

    var message;
    var image;

    if(imageInfo === 'https://firebasestorage.googleapis.com') {
        message = 'Image Received';
        image = body;
    } else {
        message = body;
        image = null;
    }

    const payload = {
        tokens: tokens,
        notification: {
            title: sender,
            body: message,
        },
        android: {
            notification: {
                channel_id: "roofdeck_default",
                title: sender,
                body: message,
                notification_priority: 'priority_max',
                color: '#DDE9F7',
                icon: '@mipmap/ic_launcher',
                image_url: image,
            },
        },  // El Codigo Comentariado aqui es para mostrar Badge en 1 con nuevos chats.
        apns: {
            payload: {
                aps: {
                    badge: 1,
                },
                fcm_options: {
                    image: image,
                  },
            },
            webpush: {
                headers: {
                  image: image,
                }
              },
        }, // Hasta Aqui el Codgio del Badge.
        // android: {
        //     notification: {
        //         notificationCount: 0,
        //         channelId: 'roofdeck_default',
        //     }
        // }
    };
    
    fcm.sendMulticast(payload).then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
        return {success: true};
    }).catch((error) => {
        console.log('Error on sent message:', error);
        return {error: error.code};
    });

});

The problem is that sometimes the image field would be null (when the user only sends text) and it should not send any images.

Any ideas on how to fix the behavior.

Kind Regards

0 Answers
Related