无法在 AppDelegate 的 rootViewController 上显示 alertViewController
Can't present alertViewController on rootViewController in AppDelegate
我想在应用程序启动时在 AppDelegate 的 rootViewController 上显示 alertViewController。这里的代码片段:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
return true
}
警报未出现在 rootViewController 上。请帮助我。
原因是视图尚未加载,如果您查看控制台,您可能会发现这样的日志:
Warning: Attempt to present on 'swiftHere.ViewController: 0x7ff289007740' whose view is not in the window hierarchy!
您可以调度它直到 rootViewController 加载:
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
我想在应用程序启动时在 AppDelegate 的 rootViewController 上显示 alertViewController。这里的代码片段:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
return true
}
警报未出现在 rootViewController 上。请帮助我。
原因是视图尚未加载,如果您查看控制台,您可能会发现这样的日志:
Warning: Attempt to present on 'swiftHere.ViewController: 0x7ff289007740' whose view is not in the window hierarchy!
您可以调度它直到 rootViewController 加载:
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}