首页 > 解决方案 > 重新安装应用后 Firebase 消息无法正常工作

问题描述

我遇到了一个非常奇怪的问题。卸载并重新安装我的 iOS 11 应用程序(以 swift 编码)后,我必须多次启动该应用程序(10 到 20 次),然后我的 firebase 消息才能再次工作。我在代码中没有任何更改(有时我只是等待一个小时左右),并且由于某种原因,Firebase 消息通知似乎仅在多次重新启动我的应用程序后才起作用。对我的应用程序来说,能够在首次打开时立即接收通知非常重要,因为我的应用程序基本上依赖于它们。我只需要找到一种方法来让通知在我安装后首次启动应用程序时工作。我附上了我的代码的图像。(我启用了 method_swizzling)

如果有人可以帮助我,我将不胜感激。我已经看到 youtube 视频做我正在做的同样的事情,他们能够让消息立即工作。我已经尝试了很多我在网上看到的东西和其他看起来像这样的问题,但他们的方法似乎都不起作用。非常感谢任何试图提供帮助的人!

[编辑]

这是应用程序启动功能的代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    application.statusBarStyle = ColorScheme.isDark ? .lightContent : .default
    FirebaseApp.configure()
//      Messaging.messaging().delegate = self
//      Messaging.messaging().shouldEstablishDirectChannel = true
//      UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in }
//      application.registerForRemoteNotifications()
    setupMessaging(application: application)
}

这是实际连接和设置我的 Firebase 消息的代码:

extension AppDelegate {
    func setupMessaging(application: UIApplication) {
        Messaging.messaging().delegate = self
        Messaging.messaging().shouldEstablishDirectChannel = true
        print("channel established", Messaging.messaging().isDirectChannelEstablished)

        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
        //TODO: Change for release
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {

    }
}

这是我收到通知时调用的调试函数:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("I got a notification")
    print(userInfo)
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("remote message received")
}

PS 我的 AppDelegate 扩展了 MessagingDelegate 和 UNUserNotificationCenterDelegate

标签: iosswiftfirebasenotificationsfirebase-cloud-messaging

解决方案


请检查以下代码

import Firebase
import FirebaseMessaging



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    Messaging.messaging().delegate = self

    //REMOTE NOTIFICATION

    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 })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    Messaging.messaging().delegate = self

    let token = Messaging.messaging().fcmToken
    print("FCM token: \(token ?? "")")

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self
    } else {
        // Fallback on earlier versions
    }
    return true
}

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

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    // Print full message.
    print(userInfo)
}

// This method will be called when app received push notifications in foreground
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
}


// MARK:- Messaging Delegates
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            print("Error fetching remote instange ID: \(error)")
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
        }
    }
}


    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("received remote notification")
    }
}

推荐阅读