本地化从 Firebase 发送的通知
Localise notifications sent from Firebase
有没有办法翻译/本地化从 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 云函数发送的,我想访问此数据对象和translate/localize发送的消息。
我查看了提供的几种方法,但它们似乎只在应用程序位于前台时才拦截通知,这不是我感兴趣的。
从服务器发送的负载:
const payload = {
notification: {
title: 'Friend request',
body: senderName + ' wants to add you as a friend'
},
data: {
senderUserId: friendRequestFrom,
type: 'friendRequest'
}
}
因为您已经在使用云功能,实现这一点的一种方法是使用 Google Cloud Translation API. There is a 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.
}
使用 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
被传递到您应用程序的通知中。
有没有办法翻译/本地化从 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 云函数发送的,我想访问此数据对象和translate/localize发送的消息。
我查看了提供的几种方法,但它们似乎只在应用程序位于前台时才拦截通知,这不是我感兴趣的。
从服务器发送的负载:
const payload = {
notification: {
title: 'Friend request',
body: senderName + ' wants to add you as a friend'
},
data: {
senderUserId: friendRequestFrom,
type: 'friendRequest'
}
}
因为您已经在使用云功能,实现这一点的一种方法是使用 Google Cloud Translation API. There is a 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.
}
使用 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
被传递到您应用程序的通知中。