简体   繁体   English

Firebase 通知未显示 IOS 但消息显示在控制台上

[英]Firebase notifications not showing up IOS but the message shows on console

I have a problem while using Firebase push notifications on IOS devices.我在 IOS 设备上使用 Firebase 推送通知时遇到问题。 I send the message from the firebase console and i get it on the log but it is not showing any notification on the devices ive tried.我从 firebase 控制台发送消息,并在日志中获取它,但它没有在我尝试过的设备上显示任何通知。

I have been searching around for posts with similar problems and i have tried everything i have found but it is still not working.我一直在四处寻找有类似问题的帖子,我已经尝试了我发现的一切,但它仍然无法正常工作。

I created the project on firebase, downloaded the google service info file and placed it on the root of the project, turned notifications on on xcode, set priority of messages on high and did a couple of changes.我在 firebase 上创建了项目,下载了 google 服务信息文件并将其放在项目的根目录下,在 xcode 上打开通知,将消息的优先级设置为高,并做了一些更改。

I also added both 'Firebase/Core' and 'Firebase/Messaging' to the podfile.我还在 podfile 中添加了“Firebase/Core”和“Firebase/Messaging”。

Right now i am using the example that Firebase provides you.现在我正在使用 Firebase 为您提供的示例。 This is my code.这是我的代码。

import UIKit
import UserNotifications

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?
  let gcmMessageIDKey = "gcm.message_id"

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

// 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 })

  // For iOS 10 data message (sent via FCM)
  FIRMessaging.messaging().remoteMessageDelegate = self

} else {
  let settings: UIUserNotificationSettings =
  UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()

// [END register_for_notifications]

FIRApp.configure()

// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
    selector: #selector(self.tokenRefreshNotification),
    name: .firInstanceIDTokenRefresh,
    object: nil)
// [END add_token_refresh_observer]

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

// 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

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
  print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler(UIBackgroundFetchResult.newData)
  }
  // [END receive_message]

  // [START refresh_token]
  func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
  print("InstanceID token: \(refreshedToken)")
}

// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
  }
  // [END refresh_token]

  // [START connect_to_fcm]
  func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
  return;
}

// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()

FIRMessaging.messaging().connect { (error) in
  if error != nil {
    print("Unable to connect with FCM. \(error)")
  } else {
    print("Connected to FCM.")
  }
}
  }
  // [END connect_to_fcm]

  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 InstanceID token.
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")

// With swizzling disabled you must set the APNs token here.
 FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
  }

  // [START connect_on_active]
  func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
  }
  // [END connect_on_active]

  // [START disconnect_from_fcm]
  func applicationDidEnterBackground(_ application: UIApplication) {
// FIRMessaging.messaging().disconnect()
// print("Disconnected from FCM.")
  }
  // [END disconnect_from_fcm]
}

// [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
// 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([.alert,.badge,.sound])

  }

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]

// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
  // Receive data message on iOS 10 devices while app is in the foreground.
  func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
// [END ios_10_data_message_handling]

The app needs to be in the background in order for it to show.该应用程序需要在后台才能显示。

I had the same problem.我有同样的问题。 Check this question to make sure everything is set up correctly.检查此问题以确保一切设置正确。

I followed this answer and this answer and this answer and this is what got it to work for me.我遵循了这个答案,这个答案和这个答案,这就是它对我有用的原因。

However, there is simple workaround for this - looks like you have to set the messaging delegate (Messaging.messaging().delegate =...) before FirebaseApp.configure()但是,有一个简单的解决方法 - 看起来您必须在 FirebaseApp.configure() 之前设置消息传递委托 (Messaging.messaging().delegate =...)

Meaning:意义:

// add this first
Messaging.messaging().delegate = self

// add this second
FirebaseApp.configure()

and:和:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
}

and this还有这个

extension AppDelegate : MessagingDelegate {

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Your Firebase FCM Registration Token: \(fcmToken)")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM