【问题标题】:Localise notifications sent from Firebase本地化从 Firebase 发送的通知
【发布时间】:2018-02-10 16:04:06
【问题描述】:

有没有办法翻译/本地化从 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(
            forName: .MessagingRegistrationTokenRefreshed,
            object: nil,
            queue: .current
        ) { [weak self] _ in
            self?.storeNotificationToken()
        }
    }

    private func storeNotificationToken() {
        Messaging.messaging().token { [weak self] token, error in
            if let error = error {
                Log.error("Error fetching FCM registration token: \(error)")
            } else if let token = token {
                // save token
        }
    }
}

}

从带有数据对象的 Firebase 云函数发送有效负载,我想访问该数据对象并翻译/本地化发送的消息。

我查看了提供的几种方法,但它们似乎是关于仅在应用程序处于前台时才拦截通知,这不是我感兴趣的。

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

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

【问题讨论】:

标签: ios swift firebase-cloud-messaging unusernotificationcenter


【解决方案1】:

因为您已经在使用云功能,所以实现此目的的一种方法是使用Google Cloud Translation API 在服务器端进行翻译。有一个 good sample 演示了如何使用 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.
}

【讨论】:

    【解决方案2】:

    在您的有效负载中使用body_loc_key 代替正文并将字符串放入您的应用程序resourceId。

    onMessageRecieved:

    String theKeyFromPayload= remotemessage.getNotification.getBodyLocalizationKey()
    
    String resourceAppStatusString=theKeyFromPayload
    Int resourceId= getResourceId(resourceAppStatusString, "string", this.getPackageName()
    
    String finalBody = getResource(). getResourceName(resourceId);
    

    finalBody 被传递到应用程序的通知中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      相关资源
      最近更新 更多