Last active
April 27, 2018 13:58
-
-
Save hamdshah/fcbd3b439d8c8a190e3009422d6b8709 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
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