Skip to content

Instantly share code, notes, and snippets.

@glm4
Created June 10, 2020 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glm4/290dad9f25a12de09eb9dc84b6a8cbe0 to your computer and use it in GitHub Desktop.
Save glm4/290dad9f25a12de09eb9dc84b6a8cbe0 to your computer and use it in GitHub Desktop.
//
// AppDelegate.swift
// Adds observer to detect changes in the *rootViewController* of the main window.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override init() {
super.init()
addObserver(self, forKeyPath: #keyPath(window.rootViewController), options: .new, context: nil)
}
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Override point for customization after application launch.
let rootVC = AppNavigator.shared.rootViewController
window?.rootViewController = rootVC
return true
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
// Check for the view controller change desired
if let firstRoot = window?.rootViewController, keyPath == #keyPath(window.rootViewController) {
//FIRST ROOT VIEW CONTROLLER
print(firstRoot)
//Remove observer if all you need is to know about the first VC
removeObserver(self, forKeyPath: #keyPath(window.rootViewController))
// You can also detect other changes like .old
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment