Ios 本地化从Firebase发送的通知

Ios 本地化从Firebase发送的通知,ios,swift,firebase-cloud-messaging,unusernotificationcenter,Ios,Swift,Firebase Cloud Messaging,Unusernotificationcenter,是否有办法翻译/本地化Firebase发送的通知 我的应用程序设置成功接收通知: extension AppDelegate: UNUserNotificationCenterDelegate { func setupNotifications() { registerForRemoteNotifications() setupNotificationTokenRefresh() } func registerForRemoteNoti

是否有办法翻译/本地化Firebase发送的通知

我的应用程序设置成功接收通知:

extension AppDelegate: UNUserNotificationCenterDelegate {

    func setupNotifications() {
        registerForRemoteNotifications()
        setupNotificationTokenRefresh()
    }

    func registerForRemoteNotifications() {
        let application = UIApplication.shared
        UNUserNotificationCenter.current().delegate = self

        application.registerForRemoteNotifications()
    }

    func setupNotificationTokenRefresh() {
        storeNotificationToken()
        NotificationCenter.default.addObserver(self,
                                           selector: #selector(storeNotificationToken),
                                           name: .InstanceIDTokenRefresh,
                                           object: nil)
    }

    @objc func storeNotificationToken() {
        if let token = InstanceID.instanceID().token() {
            UserManager.shared.updateNotificationToken(token)
        }
    }

}
有效负载通过数据对象从Firebase云函数发送,我希望访问此数据对象并翻译/本地化发送的消息

我研究了提供的几种方法,但它们似乎只在应用程序处于前台时拦截通知,这不是我感兴趣的

从服务器发送的有效负载:

const payload = {
                    notification: {
                        title: 'Friend request',
                        body: senderName + ' wants to add you as a friend'
                    },
                    data: {
                        senderUserId: friendRequestFrom,
                        type: 'friendRequest'
                    }
                }

因为您已经在使用云函数,所以实现这一点的一种方法是在服务器端使用。有一个示例演示如何使用Node.js执行此操作

例如,当新对象添加到实时数据库中的
/notifications
路径时,您正在发送通知。您可以这样做:

const Translate = require('@google-cloud/translate')
const functions = require('firebase-functions')
const projectId = 'YOUR_PROJECT_ID'
const translate = new Translate({
  projectId: projectId,
});
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

exports.sendNotification = functions.database.ref(`/notifications/{notif_id}`)
  .onWrite(event => {
    const notification = event.data.val()
    // Don't send when this isn't a new notification.
    if (event.data.previous.exists()) {
      return null
    }
    const user_id = notification.user_id
    getLocalLanguageOfUser(user_id).then(language => {
      if (language != 'en')
        translateTo(language, notification).then(localised => {
          return send(localised)
        }).catch(err => {
          return console.log(err)
        })
      } else { // it's English - no need to translate
        return send(notification)
      }
    })
})

function getLocalLanguageOfUser(user_id) {
  return new Promise((resolve, reject) => {
    // default will be 'en' for English
    firebase.database().ref(`users/${user_id}/language`)
      .once('value').then(snapshot => {
        resolve(snapshot.val() || 'en')
      })
      .catch(err => reject(err))
  })
}

function translateTo(language, notification) {
  return new Promise((resolve, reject) => {
    const text = notification.text;
    translate.translate(text, language).then(results => {
      const translation = results[0];
      resolve({
        ...notification,
        text: translation
      })
    }).catch(err => reject(err))
  })
}

function send(notification) {
  // use your current setup to send the notification.
  // 'text' key will already be localised.
}

使用
body\u loc\u key
代替有效负载中的body,并将字符串放入应用程序resourceId中

在已接收的消息上的
中:

String theKeyFromPayload= remotemessage.getNotification.getBodyLocalizationKey()

String resourceAppStatusString=theKeyFromPayload
Int resourceId= getResourceId(resourceAppStatusString, "string", this.getPackageName()

String finalBody = getResource(). getResourceName(resourceId);
finalBody
被传递到应用程序中的通知中。

可能存在的副本