Joshua
Joshua

Reputation: 13

Dismiss a UIAlertController while Loading a TableView

I programmed an UIAlertController as a Loading Screen

let waitActivityAlert = UIAlertController(title: nil, message: "Please wait...\n", preferredStyle: .alert)
let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)

func letsspin(){

    spinner.translatesAutoresizingMaskIntoConstraints = false
    waitActivityAlert.view.addSubview(spinner)


    let xConstraint = NSLayoutConstraint(item: spinner, attribute: .centerX, relatedBy: .equal, toItem: waitActivityAlert.view, attribute: .centerX, multiplier: 1, constant: 0)

    let yConstraint = NSLayoutConstraint(item: spinner, attribute: .centerY, relatedBy: .equal, toItem: waitActivityAlert.view, attribute: .centerY, multiplier: 1.4, constant: 0)

    NSLayoutConstraint.activate([ xConstraint, yConstraint])

    spinner.isUserInteractionEnabled = false


    spinner.color = UIColor.black

    spinner.startAnimating()
    let height: NSLayoutConstraint = NSLayoutConstraint(item: waitActivityAlert.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)

    waitActivityAlert.view.addConstraints([height])

    present(waitActivityAlert, animated: true)


}

and I'm loading a TableViewController in the background. While my UITableView is loading the cells, I am closing this UIAlertController with the following function:

func letsstopspin(){

    spinner.stopAnimating()
    self.waitActivityAlert.dismiss(animated: true, completion: nil)

}

And the UIAlertController doesn't dismiss and I am getting this message in the console:

Attempt to dismiss from view controller while a presentation or dismiss is in progress

So i don't know know how to solve the problem. Is there any method that can be called after the tableView() Methods? I attempted everything but the UIAlertController doesn't dismiss whatever I try.

Upvotes: 0

Views: 195

Answers (1)

Russell
Russell

Reputation: 5554

Here's one I prepared earlier. If you only make the call from one place, then you don't need a separate function, but if you think you might ever need to call it again you should do this - and a similar one for startActivityIndicator

func stopActivityIndicator()
{
    DispatchQueue.main.async(execute: {
        self.activityIndicator.stopAnimating()
    })
}

Upvotes: 2

Related Questions