Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide remote notification at specific viewcontroller when app is in foreground in swift 3

I am using firebase notifications in my chat app and I am getting it to my device.My question is how to hide remote notification at the particular view controller.when the app is in the foreground I am using

UNUserNotificationCenter, will present delegate method

to display the banner but when I am in chatViewController I don't want to show the notification banner, sound, alert like whats app feature I want..Sorry for my English

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    let userInfo:[AnyHashable:Any] =  notification.request.content.userInfo
    print("\(userInfo)")

    completionHandler([.alert, .badge, .sound])
}
like image 464
channu Avatar asked Mar 07 '23 23:03

channu


2 Answers

You can find current view controller using this methods:

extension UIViewController {
    var topViewController: UIViewController? {
        return self.topViewController(currentViewController: self)
    }

    private func topViewController(currentViewController: UIViewController) -> UIViewController {
        if let tabBarController = currentViewController as? UITabBarController,
            let selectedViewController = tabBarController.selectedViewController {
            return self.topViewController(currentViewController: selectedViewController)
        } else if let navigationController = currentViewController as? UINavigationController,
            let visibleViewController = navigationController.visibleViewController {
            return self.topViewController(currentViewController: visibleViewController)
       } else if let presentedViewController = currentViewController.presentedViewController {
            return self.topViewController(currentViewController: presentedViewController)
       } else {
            return currentViewController
        }
    }
}

And than, in func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) add this code:

if self.window?.rootViewController?.topViewController is ChatViewController {
    completionHandler([])
} else {
    completionHandler([.alert, .badge, .sound])
}
like image 193
Ilya Kharabet Avatar answered Apr 26 '23 11:04

Ilya Kharabet


Specify UNNotificationPresentationOptionNone to silence the notification completely.

UNNotificationPresentationOptionNone

like image 28
Antonio Moro Avatar answered Apr 26 '23 11:04

Antonio Moro