Last active
February 22, 2017 23:48
-
-
Save leoneparise/4647b6e89b19f20e02d5ca3fc19f51d2 to your computer and use it in GitHub Desktop.
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
import UIKit | |
import ObjectiveC | |
fileprivate struct Keys { | |
static var notificationActive = "lp_notificationActive" | |
static var notificationDeffered = "lp_notificationDeferred" | |
} | |
fileprivate extension NotificationCenter { | |
var deferredNotifications:[NotificationType] { | |
get { | |
if let value = objc_getAssociatedObject(self, &Keys.notificationDeffered) as? [NotificationType] { | |
return value | |
} else { | |
return [] | |
} | |
} | |
set { | |
objc_setAssociatedObject(newValue, &Keys.notificationDeffered, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
} | |
func fireNotifications() { | |
while let notification = deferredNotifications.popLast() { | |
post(notification) | |
} | |
} | |
} | |
extension NotificationCenter { | |
var active:Bool { | |
get { | |
if let value = objc_getAssociatedObject(self, &Keys.notificationActive) as? NSNumber { | |
return value.boolValue | |
} else { | |
return false | |
} | |
} | |
set { | |
if newValue { fireNotifications() } | |
let value = NSNumber(booleanLiteral: newValue) | |
objc_setAssociatedObject(self, &Keys.notificationActive, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
} | |
func post(deferred notification: NotificationType) { | |
if active { | |
post(notification) | |
} else { | |
deferredNotifications.insert(notification, at: 0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment