当我尝试运行项目时出现以下错误,我的项目崩溃了。
它给出了以下错误,
FaveoHelpdeskPro_Swift[1400:370341] -[FaveoHelpdeskPro_Swift.AppDelegate 窗口]:无法识别的选择器发送到实例 0x282efc980
和
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[FaveoHelpdeskPro_Swift.AppDelegate 窗口]:无法识别的选择器发送到实例 0x282efc980”
它来到以下屏幕,
并且我SceneDelegate.swift已经包含 window 对象,
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
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 }
}
Run Code Online (Sandbox Code Playgroud)
有什么问题,为什么会崩溃?
您的AppDelegate不包含window参考。window在你的中添加一个变量AppDelegate
var window: UIWindow?
Run Code Online (Sandbox Code Playgroud)
苹果文档的摘录
此属性包含用于在设备主屏幕上呈现应用程序视觉内容的窗口。
如果您的应用程序的 Info.plist 文件包含 UIMainStoryboardFile 键,则需要实现此属性
当您开始在项目中的 SceneDelegate 中初始化主 ViewController 时,一些 UI 库(如 SVProgressHUD,...)仍然指向 AppDelegate,但window那里什么也没有,所以它崩溃了。我已经遇到并成功解决了这个问题,方法如下:
AppDelegate如果不存在,则声明一个 UIWindow ,同时声明一个静态变量以快速访问 AppDelegate:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? // HERE, add it if it's not available.
static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate }
//...
}
Run Code Online (Sandbox Code Playgroud)在SceneDelegate,将 UIWindow 对象引用回 AppDelegate:
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow? // HERE
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = YOUR_VIEW_CONTROLLER()
window?.makeKeyAndVisible()
AppDelegate.shared.window = window // Connect it HERE!
}
// ....
}
Run Code Online (Sandbox Code Playgroud)注意:如果你刚刚完成步骤1,它不会崩溃,但某些UI组件会显示错误,因为它们无法确定哪个是主窗口。