Skip to content

Instantly share code, notes, and snippets.

@hamdshah
Last active April 27, 2018 13:58
Show Gist options
  • Save hamdshah/fcbd3b439d8c8a190e3009422d6b8709 to your computer and use it in GitHub Desktop.
Save hamdshah/fcbd3b439d8c8a190e3009422d6b8709 to your computer and use it in GitHub Desktop.
protocol PushHandler : class {
func shouldDisplayNotification(for item: PushNotificationItem) -> Bool
func handlePush(item: PushNotificationItem)
}
extension PushHandler {
func handlePush(item: PushNotificationItem) {}
func canHandlePush(item: PushNotificationItem) -> Bool {
return false
}
}
//Default implementation for controllers
extension UIViewController: PushHandler {
@objc func handlePush(item: PushNotificationItem) {}
//By default the notification should always be displayed
@objc func shouldDisplayNotification(for item: PushNotificationItem) -> Bool {
return true
}
}
extension UITabBarController {
override func handlePush(item: PushNotificationItem) {
for controller in self.viewControllers ?? [] {
controller.handlePush(item: item)
}
}
override func shouldDisplayNotification(for item: PushNotificationItem) -> Bool {
for controller in self.viewControllers ?? [] {
if controller.shouldDisplayNotification(for: item) == false {
return false
}
}
return true
}
}
extension UINavigationController {
override func handlePush(item: PushNotificationItem) {
for controller in self.viewControllers {
controller.handlePush(item: item)
}
}
override func shouldDisplayNotification(for item: PushNotificationItem) -> Bool {
for controller in self.viewControllers {
if controller.shouldDisplayNotification(for: item) == false {
return false
}
}
return true
}
}
//In the Appdelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//parse the item
if rootViewController.shouldDisplayNotification(for: notificationItem) {
completionHandler([.alert, .badge])
}else {
//silent push
completionHandler([])
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
...parse the item
rootViewController.handlePush(item: notificationItem)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment