1

I am using the answer located here for creating a "please wait" overlay. And I also used this answer for the asynchronous logic. What I am trying to do is create this overlay asynchronously. Ultimately, what I would like to do is just create a method which shows this overlay, and when that method call returns I want to be sure that the overlay has been fully presented. So something like this:

Helper.showPleaseWaitOverlay()
doSomeOtherTask() // when we get here, overlay should be fully presented
Helper.hidePleaseWaitOverlay()

I realize I could do something like this (e.g. use the completion callback of the present method) :

Helper.showPleaseWaitOverlay() {
    doSomeOtherTask()
    Helper.hidePleaseWaitOverlay()
}

But I really am just curious as to why the below code doesn't work. What ends up happening is that the group.wait() call just hangs and never returns.

What am I doing wrong?

// create a dispatch group which we'll use to keep track of when the async
// work is finished
let group = DispatchGroup()
group.enter()

// create the controller used to show the "please wait" overlay
var pleaseWaitController = UIAlertController(title: nil, message: "Please Wait...", preferredStyle: .alert)

// present the "please wait" overlay as an async task
DispatchQueue.global(qos: .default).async {

    // we must perform the GUI work on main queue
    DispatchQueue.main.async {
        // create the "please wait" overlay to display
        let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
        loadingIndicator.hidesWhenStopped = true
        loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
        loadingIndicator.startAnimating();

        self.pleaseWaitController!.view.addSubview(loadingIndicator)
        self.present(self.pleaseWaitController!, animated: true) {
            // the "please wait" overlay has now been presented, so leave the dispatch group
            group.leave()
        }
    }
}

// wait for "please wait" overlay to be presented
print("waiting for please wait overlay to be presented")
group.wait() // <----  Call just hangs and never completes
print("done waiting for please wait overlay to be presented")
dcp
  • 54,410
  • 22
  • 144
  • 164
  • You're calling both `group.wait()` and `group.leave()` on the same thread, but the `group.leave()` will never be called because the wait is blocking the thread so nothing else can be executed. – dan Nov 06 '17 at 16:37
  • @dan - Thanks, that makes sense. So is there another way to solve it then? – dcp Nov 06 '17 at 17:01

0 Answers0