简体   繁体   中英

Swift wait for existing async operation to finish before starting a new one

I'm working on a Swift project that uses token based authentication. When the application resumes from the background the the AppDelegate function applicationWillEnterForeground() does a check to make sure the token in memory hasn't expired (expiry date is stored in NSUserDefaults and in the token_expiry variable). If it has expired, it'll call a function to renew and get a new one.

The problem i'm facing is that while the async function is waiting for the server to reply with a new token, the user in the app could do something which requires authorisation. If this happens, since a new token has not been acquired yet the app will query the server using the old token value and data will not be retrieved.

Is there a way to ensure that the async function to renew the token has finished before we do anything else?

Set up a system of NSNotifications to inform your GUI when authentication is valid/invalid.

In your GUI, enable or disable the user controls that need authentication as appropriate when the notifications occur. How you do this will depend on your GUI design: hiding controls, greying out controls and activity indicators are some options.

Send these notifications as appropriate when you check authentication.

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