Ffltter Firebase消息:如何在指定时间向用户发送推送通知 [英] Flutter Firebase Messaging: How to send push notifications to users at specified time

查看:9
本文介绍了Ffltter Firebase消息:如何在指定时间向用户发送推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个应用程序,它有一个FiRestore集合,可以在特定时间完成项目,例如5:00pm - Go for a walk

我已经创建了一个函数,一旦用户指定了时间,我的cloud functions就可以使用Firebase Cloud Messaging创建推送通知。

但是,我希望能够在该特定时间和日期向用户发送推送通知。

这是我的cloud functions文件

async function onCreateNotification(uid, time, text) {
    const user = admin.firestore().collection('users').doc(uid).get();
    // Make this function execute at a specific time
    await admin.messaging().sendToDevice(
        user.tokens,
        {
            data: {
                user: JSON.stringify(user),
                text: JSON.stringify(text)
            }
        },
        {
            // Required for background/quit data-only messages on iOS
            contentAvailable: true,
            // Required for background/quit data-only messages on Android
            priority: "high"
        }
    ).then((response) => {
        // See the MessagingDevicesResponse reference documentation for
        // the contents of response.
        console.log('Successfully sent message:', response);
    }).catch((error) => {
        console.log('Error sending message:', error);
    });

}

推荐答案

使用Frank上面的回答,我能够成功地利用云任务和Firebase云消息传递来实现我的功能!它还有一些问题需要解决,但我想如果需要的话,以后有人可以用它。

我的代码主要基于suggested article

以下是生成的代码 cloud functions

const functions = require("firebase-functions");
const admin = require('firebase-admin')
const { CloudTasksClient } = require('@google-cloud/tasks');
admin.initializeApp()

exports.createTask = functions.https.onCall(async (data, context) => {
    log("Create Task")
    const taskClient = new CloudTasksClient();
    let { time, uid, id } = data

    // Get Date from time in format mm-dd-yyyy
    let entryDate = new Date(time[0], time[1], time[2], time[3], time[4],);
    const date = join(entryDate, '-');
    let prevEntry = await admin.firestore().doc(`/users/${uid}/${date}/${id}`).get()
    let prevEntryData = await prevEntry.data()

    if (prevEntryData.hasOwnProperty('expirationTask')) {
        // Delete old expiration task
        await taskClient.deleteTask({ name: prevEntryData.expirationTask })
    }
    // This works now! Now I should create a task on google tasks
    const todayDate = new Date()

    const expirationAtSeconds = (entryDate.getTime() - new Date().getTime()) / 1000 

    const project = JSON.parse(process.env.FIREBASE_CONFIG).projectId
    const location = 'us-central1'
    const queue = 'firestore-ttl'
    const queuePath = taskClient.queuePath(project, location, queue)
    const url = `https://${location}-${project}.cloudfunctions.net/firestoreTtlCallback`
    const docPath = `/users/${uid}/${date}/${id}`
    const payload = {
        docPath,
        uid,
    }
    const task = {
        httpRequest: {
            httpMethod: 'POST',
            url,
            body: Buffer.from(JSON.stringify(payload)).toString('base64'),
            headers: {
                'Content-Type': 'application/json'
            },
        },
        scheduleTime: {
            seconds: expirationAtSeconds
        }
    }
    const [response] = await taskClient.createTask({ parent: queuePath, task })
    const expirationTask = response.name;
    const update = { expirationTask }
    // update the entry with the expiration task name
    await admin.firestore().doc(docPath).update(update)
    log("Done with Create Task")
    return ['Success!']
})

// Callback to send message to users
exports.firestoreTtlCallback = functions.https.onRequest(async (req, res) => {
    try {
        const payload = req.body;
        let entry = await (await admin.firestore().doc(payload.docPath).get()).data();
        let tokens = await (await admin.firestore().doc(`/users/${payload.uid}`).get()).get('tokens')
        // log(entry);
        // log(tokens)
        await admin.messaging().sendToDevice(
            tokens,
            {
                data: {
                    title: JSON.stringify('App'),
                    body: JSON.stringify(entry['text'])
                }
            },
            {
                contentAvailable: true,
                priority: 'high'
            }
        ).then((response) => {
            log('Successfully sent message:')
            log(response)
            admin.firestore().doc(payload.docPath).update({ expirationTask: admin.firestore.FieldValue.delete() })
        }).catch((error) => {
            log('Error in sending Message')
            log(error)
        })
        res.status(200)
    } catch (err) {
        log(err)
        res.status(500).send(err)
    }
})

这篇关于Ffltter Firebase消息:如何在指定时间向用户发送推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆