I created a new Storyboard project in Xcode11 and trying to present a ViewController from custom class like this(which works just fine in older project):
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
appDelegate.window?.makeKeyAndVisible()
appDelegate.window?.rootViewController?.present(vc, animated: true, completion: nil)
Of course this doesn't work now because there is no window variable in AppDelegate anymore which has been moved to the SceneDelegate.
Error: Value of type 'AppDelegate' has no member 'window'
How would you make this code work now?
What I'm trying to do:
I'm trying to show a ViewController when user taps/clicks on the Push Notification Tray.
EDIT: For now I was able to make it work by creating a private static variable in SceneDelegate, and accessing that variable in my custom class:
SceneDelegate.swift
private(set) static var shared: SceneDelegate?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
Self.shared = self
}
CustomClass.swift
let sceneDeleage = SceneDelegate.shared
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
sceneDeleage?.window?.makeKeyAndVisible()
sceneDeleage?.window?.rootViewController?.present(vc, animated: true, completion: nil)
Which is probably not recommended as stated here: https://stackoverflow.com/a/58547992/9511942, but it works
EDIT2: Here is my another solution thanks to https://stackoverflow.com/a/58557634/9511942
let window = UIApplication.shared.windows.first
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
window?.makeKeyAndVisible()
window?.rootViewController = vc
If someone finds a better solution, please share.