首页 > 解决方案 > 关闭应用程序后 Firebase FCM 未更新无效令牌 Swift

问题描述

我正在使用 FCM 通过 Firebase Functions 向我的应用发送推送通知。我能够生成令牌并向用户发送推送通知,但是一旦他们完全关闭应用程序,令牌就会失效。我尝试使用下面的方法更新令牌,但它只返回我的数据库中已经存在的相同令牌,并且 Firebase Functions 说它是无效的。最终方法没有被调用。

class PushNotificationManager: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {
    let userID: String
    init(userID: String) {
        self.userID = userID
        super.init()
    }

    func registerForPushNotifications() {
        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 })
            // For iOS 10 data message (sent via FCM)
            Messaging.messaging().delegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
        }
        UIApplication.shared.registerForRemoteNotifications()
        updateFirestorePushTokenIfNeeded()
    }

    func updateFirestorePushTokenIfNeeded() {
        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                print("Error fetching remote instance ID: \(error)")
            } else if let result = result {
                print("Remote instance ID token: \(result.token)")
                var ref: DatabaseReference!
                ref = Database.database().reference()
                ref.child("users").child((Auth.auth().currentUser?.uid)!).updateChildValues(["fcmToken" :  result.token])
            }
        }

    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        var ref: DatabaseReference!
        ref = Database.database().reference()
        ref.child("users").child((Auth.auth().currentUser?.uid)!).updateChildValues(["fcmToken" :  fcmToken])
    }
}

标签: swiftfirebasepush-notificationfirebase-cloud-messaging

解决方案


推荐阅读