Flutter iOS端使用flutter_local_notification插件无法在前台显示通知的问题排查
Flutter iOS端使用flutter_local_notification插件无法在前台显示通知的问题排查
我看了你的代码,发现几个关键问题导致iOS前台无法显示通知,咱们一步步来修复:
1. AppDelegate未正确配置UNUserNotificationCenter代理
这是iOS前台显示通知的核心要求——当App在前台时,系统会通过代理询问是否允许显示通知,你的代码里缺少这部分关键逻辑:
修改AppDelegate.swift:
- 让AppDelegate明确遵守
UNUserNotificationCenterDelegate协议 - 正确设置代理(无需
as?强制转换,因为已遵守协议) - 添加前台通知显示的代理方法
修改后的完整AppDelegate代码:
import Flutter import UIKit import GoogleMaps import UserNotifications // 别忘导入通知框架 @main @objc class AppDelegate: FlutterAppDelegate, UNUserNotificationCenterDelegate { // 声明遵守代理协议 override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GMSServices.provideAPIKey("AIzaSyCx2Ncf8fdPLKLVGCbJvecpr-jnaApiLeo") // 配置通知代理 if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self // 直接设置为当前实例 } GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } // 实现前台通知展示的代理方法 @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 配置前台要展示的通知选项,按需调整 completionHandler([.alert, .sound, .badge]) } }
2. 检查FCM前台通知展示设置
你的requestPermissions方法里调用了:
await fcm.setForegroundNotificationPresentationOptions( alert: false, sound: true, badge: true, );
这里把alert设为false,如果你的测试是通过FCM触发的通知,这会直接导致前台不显示弹窗;如果是直接调用showNotification,这个设置不影响,但建议如果需要FCM前台显示alert的话,把alert改成true。
3. 确认iOS通知权限状态
你代码里的权限请求逻辑是正确的,但可以在showNotification方法里添加权限状态打印,确认用户已授予alert权限:
// 在showNotification方法开头添加(可选) if (Platform.isIOS) { final iosPlugin = _flnp.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>(); final settings = await iosPlugin?.getNotificationSettings(); Logger.logDebugInfo('iOS notification settings: $settings'); }
4. 验证NotificationDetails配置
你的_details里的DarwinNotificationDetails已经正确设置了所有present选项为true,这部分没问题,确保iOS项目里已正确配置通知权限(项目设置->Signing & Capabilities->添加Push Notifications和Background Modes->勾选Remote notifications)。
做完以上修改后,重新打包iOS应用,点击按钮测试,前台应该就能正常显示通知了。
内容来源于stack exchange
相关产品推荐
相关产品推荐

