【发布时间】:2018-05-19 22:23:01
【问题描述】:
我正在编写一些代码让用户点击一个按钮登录,登录成功后,如果有可用的数据,请立即再次调用从系统中提取数据。我对需要/不需要将代码包装在不同线程块中的位置有点困惑。鉴于我正在主线程上进行 UI 工作,我可以将所有内容都放在 DispatchQueue.main.async 中吗?这是我的代码流程 - 我想知道是否有人可以审查并让我知道我是否在异步/主线程块中包装了正确的代码结构。
let messageFrame = AlertCreator.progressBarDisplayer(view: self.view, message: "Loading", true)
DispatchQueue.main.async(execute: {
//Present loading spinner while call is made
self.view.addSubview(messageFrame)
//Make an AUTH call using URLSession.shared.dataTask (with callback)
UserSecurityService.AuthenticateUser(username: self.txtUsername.text!, password: self.txtPassword.text!)
{ (authenticationResponse) -> () in
if (authenticationResponse.Status == ResponseCode.LOGIN_SUCCESS)
{
//If this user logged in successfully, and now need to import data, then do so, otherwise just proceed to the app.
if (authenticationResponse.Value!.HasDataForImport) {
//Make ANOTHER async call using URLSession.shared.dataTask (with callback)
UserDataService.GetUserSettings()
{ response in
//Remove the spinner
messageFrame.removeFromSuperview()
if (response.Status == ResponseCode.OK)
{
//Success, go to dashboard
self.presentHomeViewController()
}
else {
//Show alert failure, with clicking 'ok' firing a callback to take the user to the dashboard
}
}
}
else {
//Data does not exist, so just stop the spinner and take the user to the dashboard
self.presentHomeViewController()
}
else if (authenticationResponse.Status == ResponseCode.INVALID_USERNAME_PASSWORD) {
//User entered the wrong username/password
messageFrame.removeFromSuperview()
<alert is created/presented here>
}
}) //main dispatch async execute
如果您注意到,我正在进行异步调用以进行身份验证,这会在 UI 上执行某些操作(显示微调器以防止任何其他活动,检查登录是否成功,并删除微调器。它还可能会显示一个警报,然后将用户带到视图控制器。
我的具体问题是:
- 我是否应该不将整个块包装在 DispatchQueue.main.async 中,但是 而只有两个网络电话?我已经完成了各种组合,其中大多数都有效(还有一些崩溃了),所以我不完全确定我是否只需要 DispatchQueue.main.async,或者需要嵌套在其中的东西,例如 DispatchQueue.global (qos: DispatchQoS.QoSClass.userInteractive).async 也是?
- 我应该包装每个网络电话,还是只包装外部电话
- 我是否应该将与 UI 相关的内容包装在它们自己的块中,例如当我呈现警报、视图控制器甚至停止时 微调器? 3.
感谢您提供的任何帮助/建议!
【问题讨论】:
-
简而言之,我会说 1) 在主线程上完成所有与 UI 相关的工作。(显示警报、微调器等)2) 对于任何其他工作,您可以使用全局队列,并相应地设置您的优先级。这将包括(网络电话等)
标签: ios swift asynchronous grand-central-dispatch ui-thread