In a popover page, I'm trying to store some data in CoreData, and I need to show a loading view until the process is done.
I found a good and easy way, using a alert controller to show a loading label. In the function, I added a shouldPresent
Boolean to make it false when the coreData process is done and hide the alert.
private func presentLoadingView(shouldPresent: Bool) {
let alert = UIAlertController(title: nil, message: "Retrieving Owner Data", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 3, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.style = UIActivityIndicatorView.Style.medium
loadingIndicator.startAnimating()
alert.view.addSubview(loadingIndicator)
presentAnimated(alert)
if !shouldPresent {
alert.dismiss(animated: true)
}
}
The problem is, when I use
dismiss(animated: true)
the entire popover will be dismissed and when I use
alert.dismiss(animated: true)
Nothing happen, could anyone help me on this. Thanks in advance.
CodePudding user response:
Try replaceing
presentAnimated(alert)
if !shouldPresent {
alert.dismiss(animated: true)
}
with
if shouldPresent {
presentAnimated(alert)
}
It seems it will do the work , accroding to your example code.
CodePudding user response:
I think using alert view for loading is not good enough for your needs.
You can use this extension easily for showing a loading view.
extension UIViewController{
func showActivityIndicator(){
DispatchQueue.main.async {[weak self] in
guard let self = self else {return}
let indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
indicator.backgroundColor = UIColor.init(hexString: "#010101").withAlphaComponent(0.6)
indicator.layer.cornerRadius = 6
indicator.center = self.view.center
indicator.hidesWhenStopped = true
indicator.color = UIColor(hexString: "#FFEE00")
indicator.style = UIActivityIndicatorView.Style.large
indicator.startAnimating()
self.view.isUserInteractionEnabled = false
indicator.tag = 1000000
for subView in self.view.subviews{
if subView.tag == 1000000{
print("Already Added")
return
}
}
self.view.addSubview(indicator)
}
}
func hideActivityIndicator(){
DispatchQueue.main.async { [weak self] in
guard let self = self else {return}
let indicator = self.view.viewWithTag(1000000) as? UIActivityIndicatorView
indicator?.stopAnimating()
indicator?.removeFromSuperview()
self.view.isUserInteractionEnabled = true
indicator?.isHidden = true
}
}
}
In your view controller just call self.showActivityIndicator() when you want to show loader and call self.hideActivityIndicator() for dismiss the loader.