代码之家  ›  专栏  ›  技术社区  ›  Vladimir Mironov

Ionic 3 phonegap推送插件如何堆叠firebase通知

  •  0
  • Vladimir Mironov  · 技术社区  · 7 年前

    我有一个应用程序,每当数据库项发生更改时,它都会向用户发送推送通知。然而,问题是每当我发送通知时,它都会在通知抽屉中创建一个新项目。但我想做的是将这些通知堆叠或分组,这样所有通知都只有一个条目,比如“9个条目已更改”。

    我如何使用Ionic 3、phonegap push插件和firebase实现这一点?

    这是我当前的代码:

      const options: PushOptions = {
            android: {
              senderID: SENDER_ID
            },
            ios: {
              alert: 'true',
              badge: true,
              sound: 'false'
            },
            windows: {},
            browser: {
              pushServiceURL: 'http://push.api.phonegap.com/v1/push'
            }
          },
          pushObject: PushObject = this.push.init(options);
    
        pushObject.on('registration').subscribe((registration: any) => {
          this.afDatabase.list('/users')
            .update(`/${user.uid}/devices/${registration.registrationId}/`, {isKept: true});
        });
        pushObject.on('error').subscribe(error => alert('Error with Push plugin' + JSON.stringify(error)));
    

    我在firebase函数中拥有:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    const _ = require('lodash');
    
    admin.initializeApp(functions.config().firebase);
    
    exports.onItemsListItemAdd = functions.database.ref('/items-list/{item_id}').onCreate(event => {
        let payload = {
            notification: {
                title: 'Items list',
                body: `Added: ${event.data.val().itemName} [${event.data.val().itemNumber}]`,
                icon: 'default'
            }
        };
    
        return sendToDevices(payload);
    });
    
    exports.onItemsListItemUpdate = functions.database.ref('/items-list/{item_id}').onUpdate(event => {
        let payload = {
            notification: {
                title: 'Items list',
                body: `Updated: ${event.data.val().itemName} [${event.data.val().itemNumber}]`,
                icon: 'default'
            }
        };
    
        return sendToDevices(payload);
    });
    
    exports.onItemsListItemDelete = functions.database.ref('/items-list/{item_id}').onDelete(event => {
        let payload = {
            notification: {
                title: 'Items list',
                body: `Deleted: ${event.data.previous.val().itemName} [${event.data.previous.val().itemNumber}]`,
                icon: 'default'
            }
        };
    
        return sendToDevices(payload);
    });
    
    function sendToDevices(payload) {
        const deviceTokens = admin.database().ref('/users').once('value');
    
        return deviceTokens.then(allTokens => {
            if (allTokens.val()) {
                // Listing all tokens.
                const tokens = _(allTokens.val())
                    .mapValues(user => user.devices)
                    .values()
                    .map(device => Object.keys(device))
                    .flatten()
                    .value();
    
                // Send notifications to all tokens.
                return admin.messaging().sendToDevice(tokens, payload).then(response => {
                    // For each message check if there was an error.
                    const tokensToRemove = [];
                    response.results.forEach((result, index) => {
                        const error = result.error;
                        if (error) {
                            console.error('Failure sending notification to', tokens[index], error);
                            // Cleanup the tokens who are not registered anymore.
                            if (error.code === 'messaging/invalid-registration-token' ||
                                error.code === 'messaging/registration-token-not-registered') {
                                tokensToRemove.push(allTokens.ref.child(tokens[index]).remove());
                            }
                        }
                    });
                    return Promise.all(tokensToRemove);
                });
            }
        });
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Vladimir Mironov    7 年前

    在查阅了官方文件和一些经验之后,我终于找到了答案。基本上,我需要做的是将推送通知中的“通知”字段替换为“数据”字段,并赋予其不同的属性。请注意,当且仅当您完全删除“通知”字段时,给定的代码才有效。

    以下是当前有效载荷:

    let payload = {
        data: {
            title: 'Items list',
            message: `Added: ${event.data.val().itemName} [${event.data.val().itemNumber}]`,
            style: 'inbox',
            summaryText: 'There are %n% notifications'
        }
    };
    

    其中“style”属性使Ionic堆叠通知。

    如果使用“notification”属性而不是“data”,则每次推送都会在通知阴影中创建新通知。

    还请注意,您可以将collapseKey选项添加到请求中,以便在消息尚未到达时仅向用户显示最新消息。你可以这样做:

    const options = {
        collapseKey: 'sl_update'
    };
    
    admin.messaging().sendToDevice(tokens, payload, options);
    

    有关更多信息,请参阅 https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#stacking