简体   繁体   English

Swift等待现有的异步操作完成后再开始新的操作

[英]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. 我正在使用基于令牌的身份验证的Swift项目。 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). 当应用程序从后台恢复时,AppDelegate函数applicationWillEnterForeground()进行检查以确保内存中的令牌尚未到期(到期日期存储在NSUserDefaultstoken_expiry变量中)。 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. 设置一个NSNotifications系统,以在身份验证有效/无效时通知您的GUI。

In your GUI, enable or disable the user controls that need authentication as appropriate when the notifications occur. 在您的GUI中,在发生通知时启用或禁用需要身份验证的用户控件。 How you do this will depend on your GUI design: hiding controls, greying out controls and activity indicators are some options. 如何执行此操作将取决于您的GUI设计:隐藏控件,将控件显示为灰色和活动指示器是一些选项。

Send these notifications as appropriate when you check authentication. 在检查身份验证时,适当发送这些通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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