Last active
March 13, 2017 10:15
-
-
Save ysoftware/bf210eb7d7545037029300648b853386 to your computer and use it in GitHub Desktop.
Notification center observers for multiple notifications with block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIViewController { | |
/** | |
Adds an observer with block for a notification. | |
- returns: A handle to remove observer. | |
- parameters: | |
- name: Notification name. | |
- object: Specify object you only want to listen to. | |
- block: Block to run when notification observed. | |
- Important: | |
The block is run synchronously on the main thread. | |
To unregister observations, you pass the object returned by this method to removeObserver(_:). | |
*/ | |
func observe(_ name: Notification.Name, for object: Any? = nil, with block: @escaping (Notification) -> Void) -> NSObjectProtocol { | |
return NotificationCenter.default.addObserver(forName: name, object: object, queue: .main, using: block) | |
} | |
/** | |
Adds an observer with block for multiple notifications. | |
- returns: Array of handles for removing observers. | |
- parameters: | |
- names: Notification names (divided by comma). | |
- object: Specify object you only want to listen to. | |
- block: Block to run when notification observed. | |
- Important: | |
The block is run synchronously on the main thread. | |
To unregister observations, you pass the object returned by this method to removeObserver(_:). | |
*/ | |
func observe(_ names: Notification.Name..., for object: Any? = nil, with block: @escaping (Notification) -> Void) -> [NSObjectProtocol] { | |
var observers:[NSObjectProtocol] = [] | |
names.forEach { observers.append(observe($0, for: object, with: block)) } | |
return observers | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment