显示请等待swift异步叠加

时间:2017-11-06 15:08:35

标签: swift asynchronous

我正在使用位于here的答案来创建“请稍候”叠加层。我还使用this answer作为异步逻辑。我想要做的是异步创建这个叠加层。最终,我想要做的只是创建一个显示此叠加层的方法,当该方法调用返回时,我想确保叠加层已完全呈现。所以像这样:

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

我意识到我可以做这样的事情(例如使用present方法的完成回调):

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

但我真的很好奇为什么下面的代码不起作用。最终发生的事情是group.wait()电话会挂起而永不返回。

我做错了什么?

// 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")

0 个答案:

没有答案