Firebase | Удаленное уведомление не отображается, swift 3.0

У меня проблема с тем, что уведомления Firebase Remote не отображаются. Мои уведомления включены в Target -> features, также установлена ​​Firebase. На веб-сайте Firebase, когда я пытаюсь отправить уведомление, оно мгновенно закрывается. Получено 0 устройств.

Это мой код:

    import UIKit
    import UserNotifications

    import Siren

    import Firebase
    import FirebaseDatabase
    import FirebaseInstanceID
    import FirebaseMessaging

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

        var window: UIWindow?

        override init() {
            super.init()
            FIRApp.configure()
            FIRDatabase.database().persistenceEnabled = true
        }

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

    //
    let notificationSettings = UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil)

    UIApplication.shared.registerUserNotificationSettings(notificationSettings)

    application.registerForRemoteNotifications()
    application.registerUserNotificationSettings(notificationSettings)


    return true
}

И вот что это показывает в Firebase:

введите здесь описание изображения

Если вам нужна другая информация, просто спросите.

Спасибо за помощь.

ОБНОВЛЕНИЕ (я добавил код):

appDelegate:

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.
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        // Print full message.
        print("%@", userInfo)
    }
    // [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()
    }

didFinishLaunchingWithOptions:

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

Другой код:

// [START connect_to_fcm]
    func connectToFcm() {
        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 applicationDidBecomeActive(_ application: UIApplication) {
        connectToFcm()
    }
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
    FIRMessaging.messaging().disconnect()

person user6083214    schedule 02.11.2016    source источник


Ответы (1)


У меня была такая же проблема, и в моем случае решение состояло в том, чтобы удалить строку FirebaseAppDelegateProxyEnabled из файла info.plist. Однако я также не вижу, чтобы вы использовали didReceiveRemoteNotification и наблюдателей.

Добавьте это также в свой appDelegate:

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.
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        // Print full message.
        print("%@", userInfo)
    }
    // [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()
    }

И я тоже не вижу наблюдателя в didFinishLaunchingWithOptions:

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

Можете ли вы также протестировать это, чтобы увидеть, подключен ли пользователь к облачным сообщениям или нет:

// [START connect_to_fcm]
    func connectToFcm() {
        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 applicationDidBecomeActive(_ application: UIApplication) {
        connectToFcm()
    }
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
    FIRMessaging.messaging().disconnect()

Кроме того, вы можете сказать, какой статус находится в консоли Firebase после отправки уведомления.

person Tarvo Mäesepp    schedule 02.11.2016
comment
Все добавил. Там написано, что каждый открытый Connected to FMC. Но если я попытаюсь отправить уведомление, оно все равно не появится, и Firebase не ответит (безумное завершение). Вы можете мне помочь? Спасибо чувак! - person user6083214; 03.11.2016
comment
Вы удалили строку из info.plist, как я сказал? Вы уверены, что разрешили уведомления в настройках? - person Tarvo Mäesepp; 03.11.2016
comment
FirebaseAppDelegateProxyEnabled удален, как вы сказали. Уведомление находится в Targets - ›AppName -› Capabilities - ›Push-уведомления включены! - person user6083214; 03.11.2016