Skip to content

Instantly share code, notes, and snippets.

@OhItsShaun
Created March 29, 2020 18:24
Show Gist options
  • Save OhItsShaun/44f12249ef8661c4e3e480e0ba9fc11c to your computer and use it in GitHub Desktop.
Save OhItsShaun/44f12249ef8661c4e3e480e0ba9fc11c to your computer and use it in GitHub Desktop.
Observing window key changes in Marzipan
import UIKit
extension NSNotification.Name {
static let didResignKey = Self.init("UISBHSMainHostWindowDidResignKeyNotification")
static let didBecomeKey = Self.init("UISBHSMainHostWindowDidBecomeKeyNotification")
}
extension Notification {
func extractUIWindow() -> UIWindow? {
let UINSWindow = object as AnyObject // Apple private `UINSWindow` type
let keyWindow = UINSWindow.value(forKey: "keyUIWindow") as? UIWindow
return keyWindow
}
}
func yourFunctionToObserveTheWindow(_ window: UIWindow) {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(forName: .didResignKey, object: nil, queue: nil) { notification in
guard let extractedWindow = notification.extractUIWindow(), extractedWindow == window else { return }
// Update your UI now that your window is no longer key
}
notificationCenter.addObserver(forName: .didBecomeKey, object: nil, queue: nil) { notification in
guard let extractedWindow = notification.extractUIWindow(), extractedWindow == window else { return }
// Update your UI now that your window is key
}
// Don't forget to capture the token returned by the above calls to
// Notification Center & remove observer on deinit, or use selectors
// which handles removal for you.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment