Firebase推送通知:App前台无通知显示问题求助
问题排查与解决
你代码里的核心问题是把两个UNUserNotificationCenter的代理方法搞混了:
userNotificationCenter(_:didReceive:withCompletionHandler:)是处理用户点击通知后的响应逻辑userNotificationCenter(_:willPresent:withCompletionHandler:)才是App处于前台时,控制通知是否展示的方法
你把这两个方法的参数合并写在了一起,导致前台收到通知时根本不会触发正确的逻辑,自然看不到通知。
正确的代码实现
1. 拆分两个代理方法
// 处理App前台收到通知时的展示逻辑 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 这里可以处理前台收到通知的自定义逻辑,比如解析userInfo let userInfo = notification.request.content.userInfo // 指定前台展示通知的方式:横幅、角标、声音 completionHandler([.banner, .badge, .sound]) } // 处理用户点击通知后的跳转逻辑 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo // 你的页面跳转逻辑 let sb = UIStoryboard(name: "Main", bundle: nil) let otherVC = sb.instantiateViewController(withIdentifier: "HomeVC") as! UITabBarController otherVC.selectedIndex = 2 UIApplication.shared.keyWindow?.rootViewController = otherVC // 必须调用completionHandler结束处理 completionHandler() }
2. 额外检查项
- 确保在App启动时已经设置UNUserNotificationCenter的代理:
UNUserNotificationCenter.current().delegate = self - 确认已经请求了通知权限,并且包含前台展示相关权限:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } - 检查Firebase推送的payload:如果是静默推送(content-available:1),前台不会自动展示,需要你自己处理UI;如果是普通通知,确保payload里包含
alert字段。
内容的提问来源于stack exchange,提问作者submariner
相关产品推荐
相关产品推荐

