2017-08-07 79 views
0

我想加載一個主視圖控制器(ViewController)時,加載應用程序。當應用程序再次進入前景顯示另一個viewController(ConfigViewController),但我試過顯示「ViewController」而不是「ConfigViewController」,我不知道爲什麼和任何人都可以幫助,謝謝。applicationWillEnterForeground無法調用加載ViewController

的AppDelegate:

func applicationWillEnterForeground(_ application: UIApplication) { 
    let notificationName = Notification.Name.UIApplicationWillEnterForeground 
    NotificationCenter.default.post(name: notificationName, object: nil) 
} 

主視圖控制器:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let myBlog = "https://www.example.com/" 
    let url = NSURL(string: myBlog) 
    let request = NSURLRequest(url: url! as URL) 

    // init and load request in webview. 
    webView = WKWebView(frame: self.view.frame) 
    webView.navigationDelegate = self 
    webView.load(request as URLRequest) 
    self.view.addSubview(webView) 
    self.view.sendSubview(toBack: webView) 

} 

配置視圖控制器:

import UIKit 

class ConfigViewController : UIViewController { 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     NotificationCenter.default.addObserver(
      self, 
      selector: #selector(displayAlert), 
      name: NSNotification.Name.UIApplicationWillEnterForeground, 
      object: nil) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func displayAlert() { 
     let alertController = UIAlertController(title: "Information", message: "Reactivate", preferredStyle: UIAlertControllerStyle.alert) 
     let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) 

     alertController.addAction(alertAction) 
     self.present(alertController, animated: true, completion: nil) 

    } 
} 
+0

你嘗試過什麼? –

+0

我運行該應用程序,它第一次顯示「ViewController」,然後單擊HOME按鈕以後臺模式發送應用程序,然後再次單擊該應用程序呼出。該應用程序仍然顯示「ViewController」,而不是調用「ConfigViewController」。我期望每次應用程序處於活動狀態時,configurViewcontroller將再次顯示。 –

回答

0

applicationWillEnterForeground您的視圖控制器尚未在堆棧中。這會。

處理您的需求,您可以:

func applicationWillEnterForeground(_ application: UIApplication) { 
    self.window = UIWindow(frame: UIScreen.main.bounds) 
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let vcMainView: ConfigViewController = mainStoryboard.instantiateViewController(withIdentifier: "ConfigViewController") as! ConfigViewController 
    self.window?.rootViewController = vcMainView 
    self.window?.makeKeyAndVisible() 
} 

但是是重要提示,看看在你的didFinishLaunchingWithOptions你不調用另一個VC。

可以肯定的是,每次應用程序激活時,此代碼都會調用您的ConfigViewController。如果您需要處理何時何地必須顯示,這不是正確的方法。

+0

謝謝,讓我再試一次。 –

相關問題