在背景中异步呈现视图控制器

时间:2017-03-01 14:58:09

标签: ios swift background presentviewcontroller

我发送异步请求,并在收到成功后提供视图控制器。它有效。

但是,当我的应用程序处于后台时,当我收到成功并且我将它传递给前台时,我遇到了问题。视图控制器并不总是显示。

我认为这是主线程,但我不确定。

我该如何解决?

编辑:

以下是我成功后调用的函数:

func showPopup(on viewController: UIViewController) {
    let viewControllerToPresent = MyPopupViewController(nibName: "Popup", bundle: nil)

    let popup = PopupDialog(viewController: viewControllerToPresent, buttonAlignment: .horizontal, transitionStyle: .zoomIn, gestureDismissal: false)

    let button = DefaultButton(title: "Ok") {
        popup.dismiss(animated: true, completion: nil)
    }

    popup.addButtons([button])
    viewController.present(popup, animated: true, completion: nil)
}

2 个答案:

答案 0 :(得分:2)

当您的应用程序处于后台,即暂停时,Apple不允许您对用户界面进行任何实质性更改。在这种情况下,您最好的方法可能是保存您希望在返回时执行某些操作并检入App Delegates applicationDidBecomeActive方法。

答案 1 :(得分:0)

如果从后台调用UI函数,结果将无法预测。只是明确地出现在主线程上。这是一个简化的例子:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.doBackgroundStuff()
    }

    func getThread() -> String {
        return Thread.isMainThread ? "UI" : "BG"
    }

    func doBackgroundStuff() {
        // force to background
        DispatchQueue.global().async {
            print("doBackgroundStuff: this is the \(self.getThread()) thread")
            self.showPopup(on: self)
        }
    }

    func showPopup(on viewController: UIViewController) {
        print("showPopup OUTER: this is the \(self.getThread()) thread")
        // force to foreground
        DispatchQueue.main.sync {
            print("showPopup INNER: this is the \(self.getThread()) thread")
            let popup = PresentingViewController(nibName: "PresentingViewController", bundle: nil)
            viewController.present(popup, animated: true, completion: nil)
        }
    }
}

显示UI,控制台上的输出为:

doBackgroundStuff: this is the BG thread
showPopup OUTER: this is the BG thread
showPopup INNER: this is the UI thread