0

У меня возникла проблема с тем, что уведомления Firebase Remote не отображаются. Мои уведомления активируются в Target -> возможностях и Firebase. На веб-сайте Firebase, когда я пытаюсь отправить уведомление, он мгновенно закрывается. Получено 0 устройств.Firebase | Удаленное уведомление не отображается, swift 3.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:

enter image description here

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

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

UPDATE (я добавил код):

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() 

ответ

0

Я была такая же проблема а, В моем случае решение заключалось в удалении строки 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 после отправки уведомления.

+0

Добавлено все. В нем говорится, что все открытые «Подключены к FMC». Но если я попытаюсь отправить уведомление, оно все равно не появится и ответа от Firebase (Insant finish) Можете ли вы мне помочь? Спасибо чувак! – user6083214

+0

Вы удалили строку из info.plist, как я уже сказал? Вы уверены, что разрешили уведомления в настройках? –

+0

FirebaseAppDelegateProxyEnabled удаляется, как вы сказали. Уведомление находится в Targetes -> 'AppName' -> Возможности -> Push Notifications установлен в ON! – user6083214

Смежные вопросы