Skip to content

Instantly share code, notes, and snippets.

@diegosanchezr
Created May 16, 2016 20:21
Show Gist options
  • Save diegosanchezr/5e195d628689a6010638787dad32d722 to your computer and use it in GitHub Desktop.
Save diegosanchezr/5e195d628689a6010638787dad32d722 to your computer and use it in GitHub Desktop.
Typed notifications with NSNotificationCenter
public protocol BPFNotification: AnyObject {
static var notificationName: String { get }
static var payloadKey: String { get }
}
public extension BPFNotification {
public static var notificationName: String {
return NSStringFromClass(Self)
}
public static var payloadKey: String {
return "\(self.notificationName)-payload"
}
}
public extension NSNotificationCenter {
private class BPFObserverWrapper {
let notificationCenter: NSNotificationCenter
let observer: AnyObject
init(notificationCenter: NSNotificationCenter, observer: AnyObject) {
self.notificationCenter = notificationCenter
self.observer = observer
}
deinit {
self.notificationCenter.removeObserver(self.observer)
}
}
public func bpf_postNotification<Notification: BPFNotification>(sender sender: AnyObject? = nil, payload: Notification) {
let name = Notification.notificationName
let payloadKey = Notification.payloadKey
let userInfo = [payloadKey : payload]
self.postNotificationName(name, object: sender, userInfo: userInfo)
}
public func bpf_addObserver<Notification: BPFNotification>(forSender sender: AnyObject? = nil, queue: NSOperationQueue = NSOperationQueue.mainQueue(), usingBlock block: (Notification) -> Void) -> AnyObject {
let name = Notification.notificationName
let payloadKey = Notification.payloadKey
let observer = self.addObserverForName(name, object: sender, queue: queue) { (notification) in
if let payload = notification.userInfo?[payloadKey] as? Notification {
block(payload)
} else {
assert(false, "Unexpected notification received: \(notification)")
}
}
return BPFObserverWrapper(notificationCenter: self, observer: observer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment