简体   繁体   中英

How and when do I save the users APN token for firebase messaging?

I was wondering how I am supposed to save the APNs token to firebase realtime DB for use when sending notifs from cloud functions.

I tried doing it in the appdelegate here:

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
    // the FCM registration token.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        let ref = Database.database().reference()
        ref.child("APNRegistrationToken").child((Auth.auth().currentUser?.uid)!).child("token").setValue(deviceToken)//Save the users token for use when reciving notification
        // With swizzling disabled you must set the APNs token here.
        // Messaging.messaging().apnsToken = deviceToken
    }
}

This leads to an error (given that in some cases the user has not yet signed up and for that reason there is no currentUser.uid (generally i dont think I have access to the uid even when the user has signed up, in the app delegate))

How and where do I save the APNs token?

I am surprised there are no simple answers but here is how you do it:

You only need to save in one place, in the appdelegate :

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

    let dataDict:[String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    // TODO: If necessary send token to application server.
    saveTokenToFire(deviceToken: fcmToken)//Save to a chosen location in DB
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM