Swift FIRMessaging push notification token reset

2019-09-11 00:46发布

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()

ref.child("Users").child(id).child(pushToken).updateChildValues(["tokenid":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!

1条回答
疯言疯语
2楼-- · 2019-09-11 01:21

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() {
  ref.child("Users").child(id).child(pushToken).updateChildValues(["tokenid":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() {
    ref.child("Users").child(id).child(pushToken).updateChildValues(["tokenid":refreshedToken])
  }

}

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

查看更多
登录 后发表回答