2017-03-01 82 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

您不能期望在應用程序出現時顯示視圖控制器在背景中。這與蘋果的指導方針相反。 –

相關問題