【问题标题】:Swift Opening/Closing App Causes ViewController to Appear More Than OnceSwift 打开/关闭应用程序导致 ViewController 出现不止一次
【发布时间】:2019-02-13 06:44:24
【问题描述】:

我遇到了一个问题,当我“关闭并打开”一个应用程序时,同一个 ViewController 会出现两次。该应用程序的设置方式是,当用户“关闭和打开”应用程序时,它会将他们带到一个“PIN”视图控制器,在那里他们输入他们的 PIN 码。问题是当用户访问“PIN”视图控制器时,视图控制器会出现两次。我怎样才能使这种情况不会发生?另外,一旦用户输入“PIN”,我该如何让用户回到他们在“关闭然后打开”应用程序之前的最后一个页面?

删除应用程序中的代码以允许用户在“打开和关闭”应用程序时转到“PIN”视图控制器:

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()
            }
        }
    }

【问题讨论】:

    标签: ios swift uiviewcontroller appdelegate


    【解决方案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

    【讨论】:

    • 谢谢-我拿出了 DispatchQues;取出这个可以解决 ViewController 出现两次的问题吗?对于 3,我如何使用它返回到我最初使用的 ViewController??
    • 队列是一个提示它与问题无关,您应该将rootVC设置为导航并使用导航的pushVC而不是更改窗口的根目录,并且每次都会显示vc根据您当前的代码,应用程序从后台转到前台的时间,因此您可以使用 bool 值检查来处理它
    • @Sh_Khan 我注意到这是目前的事情 - 糟糕的答案告诉人们无缘无故地将 UI 内容包装在 DispatchQueue.main.async 中,并且这会被传递,直到我们最终得到像这个问题中的代码。就像病毒一样!
    • @AshleyMills 我想是的,加上一些初学者不了解队列的目的,所以他们复制、粘贴代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2016-05-12
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    相关资源
    最近更新 更多