iOS本地推送通知无法显示问题求助
iOS本地通知不显示排查方案
你的代码逻辑本身没问题,但权限请求成功后通知无法弹窗,大概率是以下场景导致的,按顺序排查:
检查App是否处于前台
iOS默认不会在App前台弹出通知弹窗,仅在后台/锁屏状态下展示。如果测试时未切到后台,即使通知触发也看不到弹窗。
解决:点击「Schedule Notification」按钮后立刻按Home键切到后台,或者把触发器时间延长(比如将timeInterval: 1.0改成5.0,留足切后台的时间)。
如果需要前台也显示弹窗,需设置通知中心代理并实现willPresent方法:// 修改NotificationManager的初始化方法 init() { UNUserNotificationCenter.current().delegate = self } // 让NotificationManager遵守UNUserNotificationCenterDelegate协议 extension NotificationManager: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { // 前台时允许弹窗、声音、角标展示 return [.alert, .sound, .badge] } }确认实际通知权限状态
requestAuthorization返回的success仅代表用户曾允许权限,但后续可能被系统设置修改,或者权限类型不全。主动获取当前权限状态验证:func checkNotificationPermissions() { UNUserNotificationCenter.current().getNotificationSettings { settings in print("Alert权限状态:\(settings.alertSetting.rawValue)") print("整体通知权限状态:\(settings.authorizationStatus.rawValue)") // 正常状态应返回authorized(1)和enabled(2) } }在「Request Permission」按钮的回调中调用该方法,确认权限确实处于开启状态。
检查设备/模拟器的系统通知设置
即使代码请求成功,系统层面可能关闭了App的通知:- 打开系统「设置」→ 找到你的App → 进入「通知」页面
- 确认「允许通知」开关处于打开状态
- 确认「提醒样式」设置为「横幅」或「提醒」(而非「无」)
验证通知是否真的被触发
可以通过监听通知触发回调确认:
在NotificationManager的代理扩展中添加:func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { print("通知已触发并被点击:\(response.notification.request.content.title)") }如果切后台后能打印这条日志,说明通知已触发,只是弹窗未显示(大概率是前台展示设置问题);如果没有日志,说明通知请求未被正确添加,可给
add(request)添加错误回调排查:UNUserNotificationCenter.current().add(request) { error in if let error = error { print("添加通知请求失败:\(error)") } }
内容的提问来源于stack exchange,提问作者Ninja G
相关产品推荐
相关产品推荐

