askaale askaale - 1 year ago 87
Swift Question

Swift FIRMessaging push notification token reset

I am currently working with push notifications in my new project right now, and I am therefore experimenting with the generation of push tokens. My question is, when do these expire? I store each users push token in my Firebase database, but I know for a fact that these tokens expire/re-generates themselves. So my question is, what is the best way to hold the push token up to date?

Would I simply do this every time the user navigates to their profile?:

let token = FIRInstanceID.instanceID().token()


You see, as of right now I am asking the user to allow push notifications right after signup, but somehow it seems that it still generates a token id even though I deny the request. So my question is, how can I keep this token id updated? Would I have to do this in AppDelegate?

Thanks. Help is much appreciated!

Answer Source

To correctly store the token in your database, you'll need to handle two cases:

  1. when the app starts
  2. when the token gets refreshed

First get the current token on app/main view starts by calling FirebaseInstFIRInstanceID.instanceID().token() in for example viewDidLoad:

if let token = FIRInstanceID.instanceID().token() {

Since the current token may not have been generated yet, you need to handle nil in this code.

Then also monitor for changes to the token by implementing tokenRefreshNotification:

func tokenRefreshNotification(notification: NSNotification) {
  if let refreshedToken = FIRInstanceID.instanceID().token() {


Also see this answer I gave to a similar use-case for Android: Update Firebase Instance ID on app update