показывает контроллер вида, когда приложение выходит на передний план, но не знаю, чтобы закрыть этот контроллер вида в Swift 4 - PullRequest
0 голосов
/ 28 апреля 2018

Я хочу перейти к текущему открытому контроллеру представления после аутентификации пользователя с паролем.

это мой код (EnterForeground) в appDelegate:

     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.
    let stb = UIStoryboard(name: "Main", bundle: nil)
    let ps = stb.instantiateViewController(withIdentifier: "psID") as! PassC_VC
    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    self.window?.makeKeyAndVisible()
    DispatchQueue.global().async {
        DispatchQueue.main.async {
            ps.modalPresentationStyle = UIModalPresentationStyle.currentContext
            appdelegate.window?.rootViewController = ps
            print("in forground")
        }
    }

}

этот код работает успешно и показывает это окно, но проблема в том, чтобы закрыть этот контроллер и показать текущий активный контроллер представления, который был открыт перед показом пароля View Controller.

это мой код PassC_VC.swift: дополнительная информация: я не использую UINavigationController или что-то еще

при нажатии кнопки ОК после ввода пароля

self.dismiss(animated: true, completion: nil)

1 Ответ

0 голосов
/ 28 апреля 2018

Вы можете только отклонить контроллеров, которых присутствует . Вы не представили «ps», вместо этого вы задали как окно rootViewController. Это означает, что это первый контроллер на экране, поэтому игнорировать его не имеет смысла.

Чтобы вернуться к контроллеру, который у вас был ранее на экране, вы можете выполнить одно из следующих действий:

ВАРИАНТ 1: ПРОСМОТР КОНТРОЛЛЕРА

содержит ссылку на этот контроллер в appDelegate, когда ваше приложение входит в foregound:

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.
    let stb = UIStoryboard(name: "Main", bundle: nil)
    let ps = stb.instantiateViewController(withIdentifier: "psID") as! PassC_VC
    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    self.window?.makeKeyAndVisible()
    DispatchQueue.global().async {
        DispatchQueue.main.async {
            ps.modalPresentationStyle = UIModalPresentationStyle.currentContext

            if let delegate = UIApplication.shared.delegate as? AppDelegate {
                //Storing the reference
                delegate.yourReferenceToPreviousController = delegate.window?.rootViewController

                //Assigning the new controller
                delegate.window?.rootViewController = ps
                print("in forground")
            }
        }
    }

}

и, нажав «ОК после нажатия пароля», выполните:

if let delegate = UIApplication.shared.delegate as? AppDelegate {
    //You can now use your stored reference to reassign the root view controller
    delegate.window?.rootViewController = delegate.yourReferenceToPreviousController
}

ВАРИАНТ 2: ПРЕДСТАВЛЕНИЕ ПРЕДЫДУЩЕГО КОНТРОЛЛЕРА ПРОСМОТРА

Или вы можете избежать сохранения ссылки на предыдущий контроллер и создать новую копию, выполнив «Нажатие кнопки ОК после ввода пароля»:

let previousController = PreviousController() //This is in code but you can initialize it via storyboard
self.present(previousController, animated: true)

ВАРИАНТ 3: ПРАВИЛЬНО ПРЕДСТАВЛЯТЬ / УДАЛЯТЬ КОНТРОЛЛЕР ВАШЕГО ВИДА

Другим подходом было бы изменить способ отображения контроллера, фактически получив visibleController и заставив его представить контроллер PassCode следующим образом:

Вы можете использовать это расширение, чтобы получить видимый контроллер:

extension UIWindow {

    func visibleViewController() -> UIViewController? {
        if let rootViewController: UIViewController = self.rootViewController {
            return UIWindow.getVisibleViewControllerFrom(vc: rootViewController)
        }
        return nil
    }

    private class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {
        if vc.isKind(of: UINavigationController.self) {
            let navigationController = vc as? UINavigationController
            return UIWindow.getVisibleViewControllerFrom(vc: navigationController!.visibleViewController!)
        } else if vc.isKind(of: UITabBarController.self) {
            let tabBarController = vc as? UITabBarController
            return UIWindow.getVisibleViewControllerFrom(vc: tabBarController!.selectedViewController!)
        } else {
            if let presentedViewController = vc.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(vc: presentedViewController)
            } else {
                return vc
            }
        }
    }
}

Затем в приложении WillEnterForegound:

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.
    let stb = UIStoryboard(name: "Main", bundle: nil)
    let ps = stb.instantiateViewController(withIdentifier: "psID") as! PassC_VC
    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    self.window?.makeKeyAndVisible()
    DispatchQueue.global().async {
        DispatchQueue.main.async {
            ps.modalPresentationStyle = UIModalPresentationStyle.currentContext

            //You get the controller that is on screen
            let visibleViewController = UIWindow.getVisibleViewControllerFrom(vc: window?.rootViewController!)
            //Then make it present the controller you want
            visibleViewController.present(ps, animated: true)
            print("in forground")
        }
    }

}

Таким образом, вы фактически представляете контроллер, чтобы вы могли:

self.dismiss(animated: true, completion: nil)

Как ты и хотел.

Надеюсь, это поможет.

...