Firebase 推送通知

Firebase Push Notifications

我已经 FCM 工作了,但是我无法让传统的横幅通知工作。

这是我的 AppDelegate.swift 文件中的内容:

import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
final class AppDelegate: UIResponder {
  var window: UIWindow?

  override init() {
    super.init()    
    FIRApp.configure()
  }
}

// MARK: - UIApplicationDelegate
extension AppDelegate: UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { _, _ in })
    UNUserNotificationCenter.current().delegate = self

    FIRMessaging.messaging().remoteMessageDelegate = self

    application.registerForRemoteNotifications()

    NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification), name: .firInstanceIDTokenRefresh, object: nil)
    return true
  }

  func tokenRefreshNotification(notification: Notification) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
      print("InstanceID token: \(refreshedToken)")
    }

    connectToFcm()
  }

  func connectToFcm() {
    FIRMessaging.messaging().connect { error in
      if error != nil {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }

  func applicationDidBecomeActive(_ application: UIApplication) {
    connectToFcm()
  }
}

// MARK: - UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    print("Message ID: \(userInfo["gcm.message_id"]!)")

    print(userInfo)

    completionHandler([.alert, .sound])
  }
}

// MARK:
extension AppDelegate: FIRMessagingDelegate {
  func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print("FIRMessagingRemoteMessage Received: \(remoteMessage.appData)")
  }
}

一切都按照documentation配置。当我通过 Firebase 上的通知控制台向我的应用程序发送消息时,我得到了控制台输出。

但是,发送通知时不会显示横幅。当应用程序处于后台时,似乎也不会发送通知 - 仅当应用程序位于前台时才会发送。

寻求帮助。提前致谢!

尝试禁用方法调配。

Add FirebaseAppDelegateProxyEnabled to info.plist and set it to NO.

然后将此代码添加到应用委托

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenTypeSandbox)
}

从设备中删除您的应用并重新安装。 请测试 application:didRegisterForRemoteNotificationsWithDeviceToken 是否被调用。如果它被调用,现在尝试从 firebase 控制台发送通知。