ios - 使用 firebase 云消息传递的 swift 通知未接收到 iPhone
问题描述
我想使用 firebase 云消息将通知从我的应用程序发送到另一个应用程序。所以我对该进程使用了这个方法 retrieveFCMToken(forSenderID: senderid)。我将这段代码添加到我的应用程序委托中:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
Messaging.messaging().apnsToken = deviceToken
let senderid = "<YOUR SENDER ID>"
Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in
print("message",message!)
}
}
这是我的应用程序委托:
import UIKit
import UserNotifications
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
// [END set_messaging_delegate]
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
return true
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
Messaging.messaging().apnsToken = deviceToken
//Code for sending to other sender ID
let senderid = "xxxxxxxx"
Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in // here i am generating the token for other sender id project
print("message",message!)
}
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
我遵循了这种情况:我有两个应用程序,即“A”和“B”。我想将通知从应用程序“A”发送到应用程序“B”。因此,我将应用 A 的发件人 ID 放入应用 B 委托文件中,并使用应用 B 为应用 A 生成了注册令牌。因此,我将生成的注册令牌放置在应用 A 的 Firebase 云消息传递控制台中,同时将通知发送到应用 B . 但是应用程序 B 没有收到通知。如何解决这个错误?我在 firebase 云消息传递的两个应用程序数据库中上传了有效的 APN 的 Auth 密钥。
解决方案
A & B 是两个独立的应用程序,因此,一个 FCM 令牌对另一个无效。每个应用都会生成仅与其 Firebase 项目相关的唯一令牌。为了从 A To B 或 B To A 发送和接收通知,您需要在每个 App 中配置两个 Firebase 项目,然后检索相应的 FCM 令牌。之后,您将能够发送和接收通知
推荐阅读
- vagrant - 每次 vagrant reload 都会删除更改吗?
- scala - 使用 circe 时如何在 Scala 中表示动态 JSON 键
- regex - 使用 UAM(用户访问管理器)插件在 Wordpress 站点中访问带有大写字母的文件时出错
- java - 如何将准备好的语句从电子表格行项目循环到 derby 数据库
- php - 我无法插入新值
- visual-studio-code - VSCode - Ctrl + Alt + L 添加奇怪的字符。需要摆脱它
- python - 使用 While 循环列出超出范围的索引
- java - 如何在多个对象上设置 S3 存储桶策略?
- java - ScheduledThreadPoolExecutor 线程在完成后保留
- verilog - 在verilog代码中可以是几个supply1网吗?如果是,是什么意思?