重新安装应用后,Firebase消息无法正常工作

时间:2018-12-22 02:11:39

标签: ios swift firebase notifications firebase-cloud-messaging

我遇到了一个非常奇怪的问题。卸载并重新安装我的iOS 11应用程序(以swift编码)后,我必须多次启动该应用程序(10到20),然后我的Firebase消息才能再次运行。我没有更改代码中的任何内容(有时只是等待一个小时左右),由于某种原因,似乎Firebase Messaging Notifications仅在重新启动我的应用程序多次后才起作用。对于我的应用程序来说,非常重要的是能够在它第一次打开时立即接收通知,因为我的应用程序基本上依赖于它们。我只需要找到一种方法,即可在安装应用程序后首次启动该应用程序时使通知生效。我已经附加了我的代码的图像。 (我启用了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 Messaging的代码:

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

P.S。我的AppDelegate扩展了MessagingDelegate和UNUserNotificationCenterDelegate

2 个答案:

答案 0 :(得分:0)

请检查以下代码

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

答案 1 :(得分:0)

我找到了答案!问题是我使用的是Firebase提供的在线控制台来发送测试消息。我想是时候注册设备了。我切换到firebase函数发送通知,然后用手机订阅了一个测试主题,从而修复了所有问题。我现在收到有关第一个应用程序启动的通知,我很高兴