如何在swift中从应用程序委派中解除当前视图控制器



我想在某些条件下从appDelegate弹出当前视图控制器,但我不知道如何做到,如果有任何想法,请帮助我。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

import UIKit
import IQKeyboardManagerSwift
let kSharedAppDelegate        = UIApplication.shared.delegate as? AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enableAutoToolbar = false
//IQKeyboardManager.shared.toolbarTintColor = .white
//IQKeyboardManager.shared.toolbarBarTintColor = ColorSet.appTheamColor
kSharedAppDelegate?.moveToSplashVC()
return true
}


func applicationDidBecomeActive(_ application: UIApplication) {
// Check we can access the application window
guard let window = UIApplication.shared.windows.first else {
return
}
// Check we can access the root viewController
guard let vc = window.rootViewController else {
return
}
// Check the root vc is the type that we want to dismiss
if vc is NoInternetPopUpViewController {
vc.dismiss(animated: true, completion: nil)
}
}

//MARK:- Show No Internet connection VC
func showNoInterNetVC() {
guard  let controller = UIStoryboard(name: Storyboards.kNoInternet, bundle: nil).instantiateViewController(withIdentifier: Identifiers.kNoInternetPopUpViewController) as? NoInternetPopUpViewController else {return}

controller.modalPresentationStyle = .overFullScreen
controller.modalTransitionStyle = .crossDissolve
kSharedAppDelegate?.window?.rootViewController?.present(controller, animated: true, completion: nil)
//window.present(controller , animated: true)
}


}

我认为pop是错误的术语,除非您使用的是导航控制器。

如果你想dismiss当前呈现的viewController,你可以像这样检查应用程序WindowrootViewController

// Check we can access the application window
guard let window = UIApplication.shared.windows.first else {
return
}
// Check we can access the root viewController
guard let vc = window.rootViewController else {
return
}
// Check the root vc is the type that we want to dismiss
if vc is NoInternetPopUpViewController {
vc.dismiss(animated: true, completion: nil)
}

我还注意到,您可能不需要通过shared属性访问应用程序singleton,因为applicationDidBecomeActive(_ application: UIApplication)已经在向您传递Application了——这一行将变为:

guard let window = application.windows.first else {

还有另一种方法可以做到这一点,在较新的iOS版本中,您可以直接访问topViewController(),因此您可以像访问UIApplication.topViewController()一样访问它。唯一的缺点是,您需要将它封装到iflet语句中,以检查它是否为空。仅供参考,如果你让你的didFinishLaunching()方法在你的应用委托中至少运行一次,那么在大多数情况下它不会为空。从而可以将视图控制器堆叠为俯视图控制器。这对你来说不是问题,因为如果是这样的话,所有其他方法都会失败。

现在,要创建一个弹出视图控制器,您只需要使用顶部视图控制器并在其导航视图控制器上执行弹出操作,或者在没有导航视图控制器的情况下可以取消它。

最新更新