SceneDelegate中出现‘couldn't find window in scope’错误,求解决方案
解决Scene Delegate中"couldn't find window in scope"错误的思路
问题场景
通常couldn't find window in scope错误多出现于AppDelegate.swift中,原因是新增的Scene Delegate,但我却在Scene Delegate中遇到了该问题。以下是我的代码:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } let storyboard = UIStoryboard(name: "Main", bundle: nil) if (UserDefaults.standard.bool(forKey: "ISRemember")) { print(UserDefaults.standard.bool(forKey: "ISRemember")) let mainTabBarController = storyboard.instantiateViewController(identifier: "tabbar") window?.rootViewController = mainTabBarController } else { } }
已尝试清理Xcode的构建文件夹、重启Xcode甚至重启Mac,但问题仍未解决。
可行解决思路
确认SceneDelegate类中存在window属性
默认Xcode生成的SceneDelegate会自带var window: UIWindow?属性,如果你的类里缺失,手动添加到类声明中:class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? // 必须存在该属性 // 其他方法实现... }正确初始化并绑定window到UIWindowScene
原代码仅判断了scene类型,未初始化window并关联到当前场景,修改代码如下:guard let windowScene = scene as? UIWindowScene else { return } // 初始化window并关联到当前windowScene window = UIWindow(windowScene: windowScene) let storyboard = UIStoryboard(name: "Main", bundle: nil) if UserDefaults.standard.bool(forKey: "ISRemember") { let mainTabBarController = storyboard.instantiateViewController(identifier: "tabbar") window?.rootViewController = mainTabBarController // 让window成为可见状态 window?.makeKeyAndVisible() }检查Storyboard与Info.plist配置
确认Main.storyboard中已设置正确的初始ViewController,同时检查Info.plist里的Scene Manifest配置,确保SceneDelegate被正确关联到应用场景,避免因配置错误导致window无法自动初始化。补全UserDefaults默认值(辅助优化)
为避免ISRemember键未初始化导致的逻辑异常,可在应用启动时默认设置该键值:// 可放在AppDelegate的application(_:didFinishLaunchingWithOptions:)方法中 if UserDefaults.standard.object(forKey: "ISRemember") == nil { UserDefaults.standard.set(false, forKey: "ISRemember") }
内容的提问来源于stack exchange,提问作者Youssef Yasser
相关产品推荐
相关产品推荐

