当用户首次登录我的应用程序时,我需要从API下载一些内容,并向他们显示我正在这样做。我在MainViewController上执行此操作:
override func viewDidAppear(_ animated: Bool) {
let alert = UIAlertController(title: nil, message: "Wait please...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.style = UIActivityIndicatorView.Style.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
let parceiroId = self.defaults.getParceiroId()
if !self.defaults.getDownloadInicialTipoEntrega() {
TipoEntregaAPI().loadTiposEntrega(parceiroId){ (dados) in
if dados != nil {
for tipoEntrega in dados!{
// Do some stuff, no errors
}
}
}
}
if !self.defaults.getDownloadInicialPedido() {
PedidoAPI().loadOrders(parceiroId){ (dados) in
if dados != nil {
for pedidos in dados!{
// Do some stuff, no errors
}
}
}
}
self.dismiss(animated: false, completion: { () in print("Done") })
}
问题是我的装载警报从未消失。它从不打印“完成”。有人可以帮我吗?
我不知道它是否有用,但我总是收到此警告:
Warning: Attempt to dismiss from view controller <MyApp.MainViewController: 0x0000000> while a presentation or dismiss is in progress!
答案 0 :(得分:2)
问题恰恰是错误所说的。呼叫self.dismiss(...)
时,您的演示文稿通话尚未完成。为了进一步说明,您正在使用present(alert, animated: true, completion: nil)
参数调用animated: true
,因此不会立即完成演示。另一方面,您正在相对较短的指令块中的同一线程上调用self.dismiss(animated: false, completion: { () in print("Done") })
,因此它会在iOS完成对话框的动画演示之前被执行,这就是您得到错误的原因。
但是,此外,在实际解决问题之前,您应该问自己是否真的想在出现对话框后立即将其关闭。从您发布的代码来看,我假设您希望在两个或两个API调用完成后将其关闭。如果是这种情况,则需要在API调用的完成块(关闭)中移动dismiss
方法调用。
答案 1 :(得分:0)
对我来说的解决方案(可以正常工作并打印“完成”):
override func viewDidAppear(_ animated: Bool) {
if !self.defaults.getDownloadInicialTipoEntrega() || !self.defaults.getDownloadInicialPedido() || !self.defaults.getDownloadInicialVitrine() {
Functions.showAlertWaiting("Wait please...", self)
}
loadDeliveryTypesNOrders { (completed) in
if completed {
self.dismiss(animated: false, completion: { () in print("Done") })
}
}
}
func loadDeliveryTypesNOrders (completion: @escaping (Bool) -> ()) {
let parceiroId = self.defaults.getParceiroId()
if !self.defaults.getDownloadInicialTipoEntrega() {
TipoEntregaAPI().loadTiposEntrega(parceiroId){ (dados) in
if dados != nil {
for tipoEntrega in dados!{
// Do some stuff, no errors
}
}
}
}
if !self.defaults.getDownloadInicialPedido() {
PedidoAPI().loadOrders(parceiroId){ (dados) in
if dados != nil {
for pedidos in dados!{
// Do some stuff, no errors
}
}
}
}
completion(true)
}