根据这个主题,我正在使用一种加载模式:
Loading an "overlay" when running long tasks in iOS
我在多个ViewController中使用相同的代码,所以我创建了一个扩展:
extension UIViewController {
func showLoading() {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: false, completion: nil)
}
func hideLoading() {
if ( presentedViewController != nil && !presentedViewController!.isBeingPresented ) {
dismiss(animated: false, completion: nil)
}
}
}
我通常使用如下代码:
self.showLoading()
callNetwork() { response in
DispatchQueue.main.async {
self.hideLoading()
....
}
}
如果网络通话花费0.5秒或更长时间,则一切正常。问题是网络速度是否太快。然后,我将收到与此类似的错误:
Warning: Attempt to dismiss from view controller <UINavigationController: 0x7ff581830a00> while a presentation or dismiss is in progress!
模态也不会消失。
我能想到的最好的解决方案是这样的(超级类而不是扩展,因为扩展不能包含变量):
class LoadingViewController: UIViewController {
var shouldDismissImmediately = false
func showLoading() {
shouldDismissImmediately = false
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: false) {
if (self.shouldDismissImmediately) {
self.dismiss(animated: false, completion: nil)
}
}
}
func hideLoading() {
if ( presentedViewController != nil && !presentedViewController!.isBeingPresented ) {
dismiss(animated: false, completion: nil)
} else {
shouldDismissImmediately = true
}
}
}
谁能想到更好的解决方案?这只是感觉不对。也许我在做一些根本错误的事情。就像-在等待网络响应时甚至应该显示这样的对话框吗?有没有更好的办法让用户等待?我需要用户意识到正在发生某些事情,与此同时,我需要他不能按下用户界面中的任何按钮。
答案 0 :(得分:0)
extension UIViewController {
func showLoading(finished: @escaping () -> Void) {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: false, completion: finished)
}
func hideLoading(finished: @escaping () -> Void) {
if ( presentedViewController != nil && !presentedViewController!.isBeingPresented ) {
dismiss(animated: false, completion: finished)
}
}
}
self.showLoading(finished: {
callNetwork() {
DispatchQueue.main.async {
self.hideLoading(finished: {
// done
})
}
}
})