在 iOS 应用程序中没有收到通过 firebase 云功能发送的推送通知,尽管我从消息控制台收到
Not receiving push notification sent via firebase cloud functions in iOS app though I get the from messaging console
我的项目设置是正确的(我相信)即:
- 在 firebase 控制台的云消息部分添加了 APNs 身份验证密钥。
- 删除通知应用委托函数:
应用程序委托函数:
extension AppDelegate: UNUserNotificationCenterDelegate {
func registerForPushNotifications() {
if !Device.isSimulator {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions,
completionHandler: {_, _ in
dispatchOnMainThread {
Messaging.messaging().delegate = self
UIApplication.shared.registerForRemoteNotifications()
}
})
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(" Failed to register for remote notifications with error: \(error)")
}
private func processNotification(_ notification: UNNotification) {
let userInfo = notification.request.content.userInfo
UIApplication.shared.applicationIconBadgeNumber = 0
print(" Notification Content Received: \(userInfo)")
if let resourcePath = Bundle.main.path(forResource: "general_notification", ofType: "m4a") {
let url = URL(fileURLWithPath: resourcePath)
audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}
}
}
extension AppDelegate {
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print(" Notification received in an state: \(application.applicationState)")
}
// MARK: Handles Silent Push Notifications
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(" Notification Content Received in Background State: \(userInfo)")
completionHandler(UIBackgroundFetchResult.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: () -> Void) {
processNotification(response.notification)
completionHandler()
}
// MARK: Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
processNotification(notification)
completionHandler([.badge, .banner, .sound])
}
}
在我的云函数中,这是我拥有的:
admin.initializeApp(functions.config().firebase);
function sendNotification(userID){
let notificationToken = db.collection('notification_tokens').doc(userID);
notificationToken.get().then(doc => {
if (!doc.exists) {
console.log(`⛔️ Cant find notification token for user ${userID}`);
} else {
const tokenData = doc.data();
const tokenID = Object.keys(tokenData)[0];
console.log(` Device Token Found with tokenID: ${tokenID}`);
const messagePayload = {
title: `${userName} just joined`,
body: `Your friend ${userName} is now on Your App`,
sound: 'general_notification.m4a',
badge: `1`
};
const notificationMessageObject = {
token: tokenID,
data: messagePayload
};
admin.messaging().send(notificationMessageObject).then((response) => {
console.log(`✅ Successfully sent message: ${response}`);
return true;
}).catch((error) => {
console.log('❌ Error sending message:', error);
return false;
});
}
}).catch(err => {
console.log('Error getting tokenID document', err);
return false;
});
}
当我通过将推送通知从 Firebase 控制台上的消息面板发送到从应用程序委托捕获的物理设备令牌来测试推送通知功能时,我在 phone、[=14 上收到了通知=]
当我 运行 一个云功能触发来获得通知时,我在日志中得到了成功响应,但我的设备没有收到通知。
它在我拥有的暂存数据库上工作,但是当我设置一个新数据库并复制旧数据库时,出现了上述情况。
我是不是漏掉了什么?
最终找到了解决方案 - node.js 云函数。
而不是这样做:
admin.messaging().send
我不得不使用:
admin.messaging().sendToDevice
最终的云函数如下所示:
const payload = {
notification: {
title: `John just joined`,
body: `Your friend John is now on your app`,
sound: 'default',
badge: `1`
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 *24
};
admin.messaging().sendToDevice(tokenID, payload, options).then(function(response) {
console.log(`✅ Successfully sent message: ${response}`);
return true;
}).catch(function(error) {
console.log('❌ Error sending message:', error);
return false;
});
希望对大家有所帮助。
我的项目设置是正确的(我相信)即:
- 在 firebase 控制台的云消息部分添加了 APNs 身份验证密钥。
- 删除通知应用委托函数:
应用程序委托函数:
extension AppDelegate: UNUserNotificationCenterDelegate {
func registerForPushNotifications() {
if !Device.isSimulator {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions,
completionHandler: {_, _ in
dispatchOnMainThread {
Messaging.messaging().delegate = self
UIApplication.shared.registerForRemoteNotifications()
}
})
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(" Failed to register for remote notifications with error: \(error)")
}
private func processNotification(_ notification: UNNotification) {
let userInfo = notification.request.content.userInfo
UIApplication.shared.applicationIconBadgeNumber = 0
print(" Notification Content Received: \(userInfo)")
if let resourcePath = Bundle.main.path(forResource: "general_notification", ofType: "m4a") {
let url = URL(fileURLWithPath: resourcePath)
audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}
}
}
extension AppDelegate {
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print(" Notification received in an state: \(application.applicationState)")
}
// MARK: Handles Silent Push Notifications
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(" Notification Content Received in Background State: \(userInfo)")
completionHandler(UIBackgroundFetchResult.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: () -> Void) {
processNotification(response.notification)
completionHandler()
}
// MARK: Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
processNotification(notification)
completionHandler([.badge, .banner, .sound])
}
}
在我的云函数中,这是我拥有的:
admin.initializeApp(functions.config().firebase);
function sendNotification(userID){
let notificationToken = db.collection('notification_tokens').doc(userID);
notificationToken.get().then(doc => {
if (!doc.exists) {
console.log(`⛔️ Cant find notification token for user ${userID}`);
} else {
const tokenData = doc.data();
const tokenID = Object.keys(tokenData)[0];
console.log(` Device Token Found with tokenID: ${tokenID}`);
const messagePayload = {
title: `${userName} just joined`,
body: `Your friend ${userName} is now on Your App`,
sound: 'general_notification.m4a',
badge: `1`
};
const notificationMessageObject = {
token: tokenID,
data: messagePayload
};
admin.messaging().send(notificationMessageObject).then((response) => {
console.log(`✅ Successfully sent message: ${response}`);
return true;
}).catch((error) => {
console.log('❌ Error sending message:', error);
return false;
});
}
}).catch(err => {
console.log('Error getting tokenID document', err);
return false;
});
}
当我通过将推送通知从 Firebase 控制台上的消息面板发送到从应用程序委托捕获的物理设备令牌来测试推送通知功能时,我在 phone、[=14 上收到了通知=]
当我 运行 一个云功能触发来获得通知时,我在日志中得到了成功响应,但我的设备没有收到通知。
它在我拥有的暂存数据库上工作,但是当我设置一个新数据库并复制旧数据库时,出现了上述情况。
我是不是漏掉了什么?
最终找到了解决方案 - node.js 云函数。
而不是这样做:
admin.messaging().send
我不得不使用:
admin.messaging().sendToDevice
最终的云函数如下所示:
const payload = {
notification: {
title: `John just joined`,
body: `Your friend John is now on your app`,
sound: 'default',
badge: `1`
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 *24
};
admin.messaging().sendToDevice(tokenID, payload, options).then(function(response) {
console.log(`✅ Successfully sent message: ${response}`);
return true;
}).catch(function(error) {
console.log('❌ Error sending message:', error);
return false;
});
希望对大家有所帮助。