I feel like there is an obvious solution to this that is on the tip of my brain, but I can’t seem to figure it out. I am using the FirebaseAuth library, so I can’t edit it (or I don’t want to go down that path). The function getIDTokenForcingRefresh()
uses dispatch_async
. This would be a lot easier if it used the async/await functionality from Swift 5.5, but I have to rely on solutions for dispatch_async
. I need to grab the output to run a Firebase function request using the token. The following obviously doesn’t work because the function will return before getIDTokenForcingRefresh()
is finished. I don’t care if the main thread is blocked because the user can’t proceed in the app until this is done.
var userToken: String {
print("FIREBASE: Getting User Token")
var token = ""
Auth.auth().currentUser?.getIDTokenForcingRefresh(true) { idToken, error in
if let error = error {
print("FIREBASE: There was an error getting the user token")
return
}
print("FIREBASE: Got user token: (idToken ?? "NONE")")
token = idToken ?? ""
}
print("FIREBASE: Token: (token)")
return token
}
2
Answers
EDIT: Thanks to vadian's comment above and HangerRash's suggestion, an async computed property is better:
Old, non-optimal semaphore way
I was able to figure this out using semaphore:
Now when I want to grab the token I use:
I obviously need to do some error handling, and this is only useful when you WANT to block the main thread, which usually isn't the right answer but works for me in this situation.
Even with a completion handler method like
getIDTokenForcingRefresh
you can take advantage ofasync/await
by wrapping the asynchronous function with completion handler in aContinuation
. The error handling is for freeAnd use it
Doesn’t
Firebase
supportasync/await
meanwhile?