Paul_D
Paul_D

Reputation: 255

swift UIActivityIndicatorView advice

I have a UIActivityIndicatorView working well. But my question is how can I prevent the app user from navigation thru the app or clicking buttons while th UIActivityIndicator is displayed? I want to force the user to wait until the code I am running is complete. Here is what I have so far. Any help would be greatly appreciated.

class ViewController: UIViewController {
    var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)

var timer = NSTimer()
    let delay = 4.5

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(activityIndicator)
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    activityIndicator.color = UIColor.redColor()


    let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
    view.addConstraint(horizontalConstraint)

    let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
    view.addConstraint(verticalConstraint)
getBalance()
}

func delayedAction(){
        // time consuming code here that will run in the background with task

dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.lblAccountBalance.text = "Account Balance " + myResult!
                        self.activityIndicator.stopAnimating();
                    })
    }

 func 
    getBalance () {
        activityIndicator.startAnimating()
        timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
        }

Upvotes: 0

Views: 364

Answers (2)

LiranT
LiranT

Reputation: 91

Simply disabling user interactions from the view controller's view might not always work as you expect. If there are any buttons outside that view which are not in the view's hierarchy, then they'll be clickable.

What you should do is to temporarily suspend user interactions at the application level:

UIApplication.shared.beginIgnoringInteractionEvents()
UIApplication.shared.endIgnoringInteractionEvents()

Upvotes: 1

Paul_D
Paul_D

Reputation: 255

Super easy!

self.view.userInteractionEnabled = false

Upvotes: 1

Related Questions