Skip to content

Instantly share code, notes, and snippets.

@egnha
Created January 13, 2018 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egnha/5772a187eb8b689d953f6c0545cce88b to your computer and use it in GitHub Desktop.
Save egnha/5772a187eb8b689d953f6c0545cce88b to your computer and use it in GitHub Desktop.
Notifications
// Jared Sinclair: https://twitter.com/jaredsinclair/status/951536021459619840
class NotificationObserver {
private var observers = [NSObjectProtocol]()
private let queue: OperationQueue
init(queue: OperationQueue = .main) {
self.queue = queue
}
deinit {
observers.forEach { NotificationCenter.default.removeObserver($0) }
}
func when(_ name: Notification.Name, perform block: @escaping (Notification) -> ()) {
let center = NotificationCenter.default
let observer = center.addObserver(forName: name, object: nil, queue: queue, using: block)
observers.append(observer)
}
}
class MyViewController: UIViewController {
private let observer = NotificationObserver()
override func viewDidLoad() {
super.viewDidLoad()
observer.when(.UIApplicationDidBecomeActive) { [weak self] _ in
// Do something
}
observer.when(.UIApplicationDidEnterBackground) { [weak self] _ in
// Do something (else)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment