我正在使用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])
}
}