【发布时间】:2017-03-30 20:58:09
【问题描述】:
我正在使用 Swift 3。
我试图做的行为是:用户点击一个按钮,一个旋转的齿轮警报控制器显示,同时它启动一个长时间运行的功能。一旦该函数执行完毕,旋转的齿轮就会消失,视图控制器也会消失。
下面的代码启动doProcessing 函数,但直到视图关闭前大约一秒钟才显示旋转齿轮。所以这不太对。
func displaySpinningGear() {
print("display spinning gear")
// show the alert window box
let activityAlertController = UIAlertController(title: "Processing", message: "Please wait while the photo is being processed.", preferredStyle: .alert)
//create an activity indicator
let indicator = UIActivityIndicatorView(frame: activityAlertController.view.bounds)
indicator.autoresizingMask = [.flexibleWidth, .flexibleHeight]
indicator.hidesWhenStopped = true
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
//add the activity indicator as a subview of the alert controller's view
activityAlertController.view.addSubview(indicator)
indicator.isUserInteractionEnabled = false // required otherwise if there buttons in the UIAlertController you will not be able to press them
indicator.startAnimating()
print("start animating")
self.present(activityAlertController, animated: true, completion: nil)
}
func onButtonClick() {
self.displaySpinningGear()
DispatchQueue.main.async {
self.doProcessing() // long running function
}
if let viewController = presentingViewController {
// This block will dismiss both current and a view controller presenting current
viewController.dismiss(animated: true, completion: nil)
}
else {
// This block will dismiss only current view controller
self.dismiss(animated: true, completion: nil)
}
}
下面的代码启动了doProcessing 函数,但视图立即消失,我可以从控制台得知我的doProcessing 函数仍在运行。这也不对。
function onButtonClick() {
DispatchQueue.global(qos: .background).async {
print("Processing")
self.doProcessing() // run in background
DispatchQueue.main.async {
self.displaySpinningGear()
}
}
if let viewController = presentingViewController {
// This block will dismiss both current and a view controller presenting current
viewController.dismiss(animated: true, completion: nil)
}
else {
// This block will dismiss only current view controller
self.dismiss(animated: true, completion: nil)
}
}
如何在显示旋转齿轮时启动背景功能并在后台功能完成运行时(而不是之前)关闭视图和警报控制器?
编辑
按照@Honey 在评论中的建议,尝试移动代码以在背景块之外旋转齿轮,但无济于事。当进程函数仍在处理时,视图会立即关闭(我可以通过打印语句来判断)。
func onButtonClick() {
DispatchQueue.main.async {
self.displaySpinningGear()
}
DispatchQueue.global(qos: .background).async {
print("Processing")
self.doProcessing() // run in background
}
if let viewController = presentingViewController {
// This block will dismiss both current and a view controller presenting current
viewController.dismiss(animated: true, completion: nil)
}
else {
// This block will dismiss only current view controller
self.dismiss(animated: true, completion: nil)
}
}
【问题讨论】:
-
在您的第二个解决方案中:尝试将
DispatchQueue.main.async { self.displaySpinningGear() }删除到DispatchQueue.global(qos: .background).async的外部。此外,将您的函数命名为process会更好。 -
@Honey 嗯,这似乎不起作用。请参阅帖子中的编辑。