2017-03-01 80 views
-1

我发送异步请求,并在成功时呈现视图控制器。有用。在后台异步呈现视图控制器

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

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

我该如何解决?

编辑:

这里是我成功后调用该函数:

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) 
} 
+0

代码在哪里?你试过了什么? – Mannopson

+0

上面的代码不显示任何在后台调用的内容。请显示所有_relevant_代码。谢谢 –

+0

没有其他相关的代码。 – Grifas

回答

2

当你的应用程序在后台,也就是停赛,苹果不允许你对用户界面进行任何更改实质性更改。在这种情况下,您最好的办法可能是保存您想要返回的东西,并检查您的App Delegates applicationDidBecomeActive方法。

+0

是的,我想我会保存,如果应用程序在后台,在willEnterForeground添加一个观察者,并做我的东西。谢谢您的回答 :) – Grifas

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 
+0

我的问题是当应用程序在异步请求期间在后台 – Grifas

+0

您不能期望在应用程序出现时显示视图控制器在背景中。这与苹果的指导方针相反。 –

相关问题