通过 Appdelegate 调用时展开 View Controller 时出错

Error unwrapping View Controller when called through Appdelegate

所以当应用程序到达前台时,我试图在当前 vc 上显示密码VC。当前,在密码 VC 上(我试图在顶部显示的 VC)具有此功能:

func present() {
        print("calling present")
        if let passcodeVC = storyboard?.instantiateViewController(withIdentifier: "IdlePasscodeVC") {
        passcodeVC.modalPresentationStyle = .overCurrentContext
        present(passcodeVC, animated: true, completion: nil)
        } else {
            print("there was an error unwrapping")
        }
    }

当应用到达前台时,我通过 AppDelegate 调用它,代码如下:

func applicationWillEnterForeground(_ application: UIApplication) { 
        print("app entered foreground")
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    if let passcodeVC = storyboard.instantiateViewController(withIdentifier: "LockVC") as?  IdlePasscodeViewController{
        passcodeVC.present()
    }
    }

修复了一个问题;但现在我收到一个错误 "Warning: Attempt to present on whose view is not in the window hierarchy!"

有办法解决这个问题吗?还是有人可以告诉我更好的方法(我已经阅读了通知中心并且可以使用监听器,但我不知道从哪里开始)。

希望密码 VC 出现在上次打开的屏幕顶部,这样当密码正确时,它可以自行关闭

可能的替代方法会有所帮助。

编辑:是否可以使用此解决方案?

检查这个我认为可以在某种程度上帮助你

func applicationWillEnterForeground(_ application: UIApplication) { 
        print("app entered foreground")
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        if let passcodeVC = storyboard?.instantiateViewController(withIdentifier: "IdlePasscodeVC") as?  IdlePasscodeViewController{
        passcodeVC.present()
        }
    }

希望对您有所帮助