iOS开发:APP前台运行时本地通知不弹出仅退出后收到如何处理
问题原因
iOS系统默认情况下,App处于前台运行状态时,本地通知不会弹出系统级的通知提示,需要手动实现UNUserNotificationCenterDelegate协议的对应方法才可实现前台弹窗。
具体修复步骤
- 第一步:在App启动入口设置通知中心的代理
如果你使用UIKit开发,在AppDelegate.swift的application(_:didFinishLaunchingWithOptions:)方法中添加如下代码:
如果你使用SwiftUI开发,可以在App主结构体的初始化方法中设置:import UserNotifications func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 新增这行代码设置通知代理 UNUserNotificationCenter.current().delegate = self return true }import UserNotifications @main struct YourApp: App { init() { UNUserNotificationCenter.current().delegate = NotificationDelegate.shared } // 其余原有代码 } - 第二步:实现通知前台展示的代理方法
UIKit开发可以直接给AppDelegate加扩展实现协议方法:
SwiftUI开发可以单独创建一个全局代理类:extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { // 返回你需要的前台通知展示样式,和你申请的权限对应即可 return [.banner, .sound, .badge] } }class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate { static let shared = NotificationDelegate() func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { return [.banner, .sound, .badge] } } - 补充优化:你当前代码中触发器的
repeats参数设置为false,通知只会触发一次,如果要实现每日定时推送的需求,需要修改为true:let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
内容的提问来源于stack exchange,提问作者George Sepetadelis
相关产品推荐
相关产品推荐

