You need to enable JavaScript to run this app. Swift开发:AppDelegate根据UserDefaults登录态判断后无法展示对应视图控制器
优惠活动
大模型
产品
解决方案
定价
更多

Swift开发:AppDelegate根据UserDefaults登录态判断后无法展示对应视图控制器

视图控制器不显示的核心原因与解决方案

问题本质不是控制器实例化逻辑写错,也不是UserDefaults读取异常(你观察到print能正常输出也验证了这一点),核心原因是代码操作的窗口实例,根本不是应用实际承载界面的目标window,常见踩坑点和解法如下:

常见踩坑原因

  • iOS13+项目默认启用SceneDelegate,AppDelegate中的window属性为空
    这是绝大多数开发者遇到这个问题的头号原因:Xcode11之后新建的项目默认开启多场景适配,应用窗口的初始化、根控制器设置的权限全部移交到SceneDelegate中,AppDelegate自带的window属性不会被系统自动实例化,你在AppDelegate里通过share?.window拿到的对象始终是nil,哪怕给它赋值,也根本影响不到实际显示界面的窗口。
  • 未手动初始化AppDelegate的window实例
    如果你是纯代码搭建的项目、没有用Storyboard作为启动入口,系统不会帮你自动创建window实例,你代码里取到的window同样是空值,所有给rootViewController的赋值操作都没有实际效果。
  • 系统默认Storyboard加载逻辑覆盖了你的设置
    带Storyboard配置的项目,系统会在didFinishLaunchingWithOptions执行完成后,自动把Storyboard中标记为初始入口的控制器设置为window的rootViewController,这个流程的执行时机晚于你写的checkDefault()调用,会把你手动设置的已登录界面直接覆盖回默认的登录页。

对应正确实现方案

方案1:适配iOS13+带SceneDelegate的默认项目

直接把根控制器判断逻辑从AppDelegate挪到SceneDelegate中,移除AppDelegate里所有操作window的代码,在SceneDelegate的场景初始化方法中完成窗口创建和判断:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    // 手动创建绑定当前场景的窗口实例
    self.window = UIWindow(windowScene: windowScene)
    let mainStoryboard = UIStoryboard(name: "Main", bundle: .main)
    
    // 读取本地登录状态
    let isLogged = UserDefaults.standard.bool(forKey: "isLogged")
    if isLogged {
        // 已登录:加载首页控制器
        let homeVC = mainStoryboard.instantiateViewController(withIdentifier: "parent_vc") as! ParentHomeViewController
        let navVC = UINavigationController(rootViewController: homeVC)
        window?.rootViewController = navVC
    } else {
        // 未登录:加载Storyboard默认的登录页
        window?.rootViewController = mainStoryboard.instantiateInitialViewController()
    }
    window?.makeKeyAndVisible()
}

方案2:兼容低版本、无SceneDelegate的项目

首先确保在AppDelegate的启动方法最开头完成window的初始化,再执行登录状态判断:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 先手动创建窗口实例,避免window为空
    self.window = UIWindow(frame: UIScreen.main.bounds)
    checkDefault()
    return true
}

func checkDefault() {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: .main)
    let isLogged = UserDefaults.standard.bool(forKey: "isLogged")
    if isLogged {
        let homeVC = mainStoryboard.instantiateViewController(withIdentifier: "parent_vc") as! ParentHomeViewController
        let navVC = UINavigationController(rootViewController: homeVC)
        window?.rootViewController = navVC
    } else {
        window?.rootViewController = mainStoryboard.instantiateInitialViewController()
    }
    window?.makeKeyAndVisible()
}

内容的提问来源于stack exchange,提问作者astroworld85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 17:15:03