Xcode 13+, iOSiOS 13+, Swift
Scenes represent instances of the app's UI and each scene maintains its own, fully-independent, state. And the app itself, which is never more than a single instance, maintains references to all of these connected scenes. And scenes are classes so they are reference-types. Therefore, simply maintain a reference to the scene itself when it is connected and then find that scene in the set of connected scenes within UIApplication.shared
.
// Create a globally-accessible variable of some kind (global
// variable, static property, property of a singleton, etc.) that
// references this current scene (itself).
var currentScene: UIScene?
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = scene as? UIWindowScene else {
return
}
// Save the reference when the scene is born.
currentScene = scene
}
func borat() {
print("great success")
}
}
// Here is a convenient view controller extension.
extension UIViewController {
var sceneDelegate: SceneDelegate? {
for scene in UIApplication.shared.connectedScenes {
if scene == currentScene,
let delegate = scene.delegate as? SceneDelegate {
return delegate
}
}
return nil
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
sceneDelegate?.borat() // "great success"
}
}