![](/img/trans.png)
[英]How to make remote notification appear in notification center when app is in the foreground?
[英]Hide remote notification at specific viewcontroller when app is in foreground in swift 3
我在我的聊天應用程序中使用了 firebase 通知,我正在將它發送到我的設備。我的問題是如何在特定的視圖控制器上隱藏遠程通知。當應用程序在我使用的前台時
UNUserNotificationCenter,將呈現委托方法
顯示橫幅,但是當我在 chatViewController 中時,我不想顯示通知橫幅、聲音、警報,例如我想要的應用程序功能..對不起我的英語
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])
}
您可以使用以下方法找到當前的視圖控制器:
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
}
}
}
然后,在func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
添加以下代碼:
if self.window?.rootViewController?.topViewController is ChatViewController {
completionHandler([])
} else {
completionHandler([.alert, .badge, .sound])
}
指定UNNotificationPresentationOptionNone使通知完全靜音。
傳遞空的 completionHandler([]) 以隱藏遠程通知。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent
notification: UNNotification,
withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) ->
Void) {
let userInfo:[AnyHashable:Any] = notification.request.content.userInfo
print("\(userInfo)")
completionHandler([])
}
這對我們有用-
AppDelegate.m
// Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionNone);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.