ios - Firebase Messenger 发送通知,但 iOS 设备未收到任何消息

标签 ios swift firebase firebase-cloud-messaging

我正在尝试获取从 Firebase Cloud Messenger 发送到单个设备的通知。我已经安装了 firebase,当我运行该程序时,控制台会打印出 fcm token ,我尝试使用该 token 向该设备发送消息(我使用的是真正的 iPhone)。该消息发送正常,但我的 iPhone 上却没有显示任何内容。我在应用程序委托(delegate)中实现了以下代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)



    if #available(iOS 10.0, *)
    {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert])          { (granted, error) in
            if granted
            {
                //self.registerCategory()
            }
        }
        // For iOS 10 data message (sent via FCM)
        Messaging.messaging().delegate = self
    }
    else
    {
        let settings: UIUserNotificationSettings =  UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    //Configuring Firebase
    FirebaseApp.configure()
    // Add observer for InstanceID token refresh callback.
    NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)


    return true
}


//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
    Messaging.messaging().appDidReceiveMessage(userInfo)
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{

    Messaging.messaging().apnsToken = deviceToken

}

@objc func tokenRefreshNotification(notification: NSNotification)
{
    if let refreshedToken = InstanceID.instanceID().token()
    {
        print("InstanceID token: \(refreshedToken)")
    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm()
{
    Messaging.messaging().shouldEstablishDirectChannel = true
}

func applicationDidBecomeActive(application: UIApplication)
{
    connectToFcm()
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")

    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

This is the response I get from the Firebase end

所以它说没有发送任何消息,我对此感到困惑,因为它是我的设备刚刚输出的 token 。

我怎样才能找到更多信息或解决这个问题?

最佳答案

在从 fcm 控制台运行消息之前,检查 .p12 文件是否已上传

enter image description here

然后实现消息处理方法 在前景和背景

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    Messaging.messaging().appDidReceiveMessage(userInfo)
    if let messageID = userInfo[gcmMessageIDKey] {
    }

    print(userInfo)
    completionHandler([.alert, .badge, .sound])

   }

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }


    completionHandler()

}

extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: (fcmToken)")
}
Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: (remoteMessage.appData)")
}
}

关于ios - Firebase Messenger 发送通知,但 iOS 设备未收到任何消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49522284/

相关文章:

android - 更改 app-ads.txt 的域后是否应该重新发布应用?

ios - 如何使图像仅在 iPhone 6/6s 上可见

ios - (BOOL) webView...没有触发所有请求

swift - Xcode 中的按钮是否有不止一层约束?

ios - Swift 中 UIPanGestureRecognizer 的奇怪问题

ios - 单击 TableView 某个部分中的任意位置后如何执行 segue?

ios - FirebaseUI 和 SDWebImage 在 CollectionViewControllerCell 的 for 循环中显示图像

swift - 尝试从 Firebase 检索数据时未调用 tableView(_ tableView : UITableView, cellForRowAt indexPath: IndexPath) 函数

javascript - Firebase firestore 设置要记录的对象数组

ios - 搜索 NSData 末尾附近的字节时出现 NSRangeException