React Native 0.73集成UserNotifications的新AppDelegate接口实现
在React Native 0.73中扩展RCTAppDelegate以支持UserNotifications
React Native 0.73引入的RCTAppDelegate已经封装了原有的UIApplicationDelegate和RCTBridgeDelegate实现,你只需要让自定义的AppDelegate继承它,同时遵守UNUserNotificationCenterDelegate协议即可,具体实现如下:
1. 修改AppDelegate.h文件
在头文件中引入UserNotifications框架,并让AppDelegate继承RCTAppDelegate同时遵守通知代理协议:
#import <RCTAppDelegate.h> #import <UserNotifications/UserNotifications.h> @interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate> @end
2. 在AppDelegate.m中实现通知相关逻辑
重写必要的方法,同时记得先调用父类的实现保证RN核心逻辑正常运行:
#import "AppDelegate.h" #import <React/RCTRootView.h> @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 先执行RN父类的初始化逻辑 [super application:application didFinishLaunchingWithOptions:launchOptions]; // 注册通知代理 UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter]; notificationCenter.delegate = self; // 请求通知权限(根据业务需求调整权限选项) [notificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) { // 处理权限申请结果 if (granted) { [application registerForRemoteNotifications]; } }]; return YES; } // 前台收到通知时的处理逻辑 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // 自定义前台通知展示方式,比如允许弹窗、声音 completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound); } // 用户点击通知后的处理逻辑 - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler { // 这里可以处理通知点击事件,比如跳转指定页面 completionHandler(); } // 如果需要处理远程通知注册成功的回调 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { // 上传deviceToken到你的服务器 } @end
注意事项
- 重写任何
UIApplicationDelegate的方法时,必须先调用[super application:...];,否则会破坏RN的核心初始化流程 RCTAppDelegate已经默认实现了原有的桥接代理逻辑,不需要再手动处理RCTBridgeDelegate的相关方法- 确保项目中已正确引入UserNotifications框架(Xcode通常会自动关联,若出现编译错误可在Build Phases的Link Binary With Libraries中手动添加)
内容的提问来源于stack exchange,提问作者ofundefined
相关产品推荐
相关产品推荐

