iOS无法接收OneSignal通知及APNs设备令牌错误问题求助
iOS通知接收问题解决方案(Flutter 3.7.12 + onesignal_flutter 3.5.1)
一、处理OneSignal废弃方法警告
这个警告提示的application:didReceiveLocalNotification:是iOS旧版通知回调方法,现已被弃用,OneSignal SDK不再调用它。虽不一定直接导致收不到通知,但修复后可避免潜在回调冲突:
- 打开iOS项目的
AppDelegate.swift(或AppDelegate.m)文件,直接删除application(_:didReceiveLocalNotification:)方法。 - 替换为
UNUserNotificationCenter的标准回调实现,示例如下:
Swift版本:
Objective-C版本:import UserNotifications class AppDelegate: FlutterAppDelegate, UNUserNotificationCenterDelegate { override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 保留原有初始化代码,新增该行 UNUserNotificationCenter.current().delegate = self GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } // 前台收到通知时,允许弹出、发声、显示角标 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .sound, .badge]) } // 用户点击通知后的回调(可按需添加业务逻辑) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { completionHandler() } }#import <UserNotifications/UserNotifications.h> @interface AppDelegate () <UNUserNotificationCenterDelegate> @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 保留原有初始化代码,新增该行 [UNUserNotificationCenter currentNotificationCenter].delegate = self; [GeneratedPluginRegistrant registerWithRegistry:self]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } // 前台收到通知的处理逻辑 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge); } // 点击通知后的处理逻辑 - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler { completionHandler(); } @end
二、解决'APNs BAD DEVICE TOKEN'错误
这个错误是通知无法送达的核心原因,按以下步骤排查:
- 环境匹配:OneSignal后台配置的APNs证书(开发/生产)必须和当前App运行环境一致。开发证书对应调试模式的App,生产证书对应App Store/Ad Hoc分发版本。
- 刷新设备令牌:卸载当前App后重新安装,让设备向APNs重新申请有效令牌,避免旧令牌过期或失效。
- Bundle ID一致性:OneSignal后台填写的Bundle ID必须和Xcode项目中的Bundle ID完全一致,大小写也不能出错。
- 检查证书有效性:登录Apple开发者后台,确认APNs证书未过期,且正确关联了对应的App ID。
三、iOS模拟器无法接收通知的问题
iOS模拟器本身不支持APNs推送,必须使用真实iOS设备测试通知功能。若需在模拟器测试,可使用Xcode内置工具:
- 打开Xcode,选择
Window > Devices and Simulators - 选中目标模拟器,右键点击
Push Notification - 上传符合APNs格式的JSON payload文件,即可发送测试通知
内容的提问来源于stack exchange,提问作者Som Gupta
相关产品推荐
相关产品推荐

