快速打开/关闭应用程序导致ViewController出现多次

时间:2018-09-07 23:03:08

标签: ios swift uiviewcontroller appdelegate

我遇到一个问题,当我“关闭并打开”一个应用程序时,同一个ViewController出现两次。该应用程序的设置方式是,当用户“关闭并打开”该应用程序时,它将带他们到“ PIN” ViewController,在此他们输入PIN码。问题是,当用户进入“ PIN” ViewController时,ViewController会显示两次。我该如何避免这种情况发生?另外,一旦用户输入“ PIN”,我该如何进行设置,以便用户可以在“关闭然后打开”应用程序之前返回上一页。

“应用程序删除”中的代码,以允许用户在“打开和关闭”应用程序时转到“ PIN” ViewController:

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

        DispatchQueue.global(qos: .background).async {
            print("This is run on the background queue")


            DispatchQueue.main.async {
                print("This is run on the main queue, after the previous code in outer block")

                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
                let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let yourVC = mainStoryboard.instantiateViewController(withIdentifier: "PINViewController") as! PINViewController

                appDelegate.window?.rootViewController = yourVC
                appDelegate.window?.makeKeyAndVisible()
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

1-您应同时删除

DispatchQueue.global(qos: .background).async
DispatchQueue.main.async

因为默认情况下代码位于主线程内

2-内部代码

applicationWillEnterForeground
例如,当您按下主屏幕按钮并再次打开应用程序时,会调用

,这不是应用程序关闭,而是应用程序在后台运行

3-使用UINavigationController来设置VC以返回到它

let nav = ////
nav.viewControllers = [vc1,vc2]
appDelegate.window?.rootViewController = nav

因此将显示vc2,并且可以返回vc1