iOS前台如何移除通知弹窗?UNUserNotificationCenterDelegate使用疑问
嘿,我来帮你搞定这个通知显示的问题!你现在遇到的情况是因为在willPresentNotification:方法里传了UNNotificationPresentationOptionAlert,在iOS 15及以后的系统里,这个选项会让通知同时弹出Alert弹窗和Banner横幅,这和你想要的效果不符对吧?
针对需求的两种解决方案
根据你“移除弹窗”的需求,分两种场景给你对应的实现:
只想显示Banner横幅,不弹出Alert弹窗(iOS 15+适配)
从iOS 15开始,Apple新增了专门的UNNotificationPresentationOptionBanner选项,用来指定前台只显示横幅。我们需要做版本适配,兼顾老系统:-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){ if (@available(iOS 15.0, *)) { // iOS15+ 仅显示横幅 completionHandler(UNNotificationPresentationOptionBanner); } else { // iOS10-14 系统前台只能显示弹窗,若不想显示弹窗就传None completionHandler(UNNotificationPresentationOptionNone); } }完全隐藏前台的通知提示(既不弹窗也不显示横幅)
如果你只是想让App在前台时完全不展示任何通知提示,直接传UNNotificationPresentationOptionNone就可以了:-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){ // 前台不显示任何通知提示 completionHandler(UNNotificationPresentationOptionNone); }
为什么之前的代码会同时出现弹窗和横幅?
在iOS 15之前,UNNotificationPresentationOptionAlert只会在前台弹出Alert弹窗;但iOS 15及以后,Apple调整了这个逻辑——指定Alert选项时,系统会同时展示弹窗和横幅,这是系统默认的新行为,所以你才会看到两种提示同时出现。
内容的提问来源于stack exchange,提问作者MahdiM
相关产品推荐
相关产品推荐

