You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在iOS AppDelegate Subscriber中向React Native发送事件?

解决方案

1. 实现AppDelegate Subscriber并获取EventEmitterService

在iOS Native模块代码中,创建遵循EXAppDelegateSubscriber协议的类,在didReceiveRemoteNotification回调里通过模块注册表获取EXEventEmitterService实例,进而向JS层发送事件:

#import <ExpoModulesCore/ExpoModulesCore.h>

@interface NotificationSubscriber : NSObject <EXAppDelegateSubscriber>
@end

@implementation NotificationSubscriber

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 获取全局模块注册表
    EXModuleRegistry *moduleRegistry = [EXModuleRegistryProvider sharedInstance].moduleRegistry;
    if (!moduleRegistry) {
        completionHandler(UIBackgroundFetchResultNoData);
        return;
    }
    
    // 从注册表中获取EventEmitter服务
    id<EXEventEmitterService> eventEmitter = [moduleRegistry getModuleImplementingProtocol:@protocol(EXEventEmitterService)];
    if (eventEmitter) {
        // 发送自定义事件到JS层,事件名和参数可按需调整
        [eventEmitter sendEventWithName:@"RemoteNotificationReceived" body:userInfo];
    }
    
    // 完成后台回调,根据实际情况返回对应结果
    completionHandler(UIBackgroundFetchResultNewData);
}

@end

2. 注册AppDelegate Subscriber

在你的Native模块类中,重写appDelegateSubscribers方法,返回上面的Subscriber实例,确保Expo能识别并注册该订阅者:

#import <ExpoModulesCore/ExpoModulesCore.h>

@interface YourCustomModule : EXModule
@end

@implementation YourCustomModule

EX_EXPORT_MODULE(YourCustomModule);

// 注册AppDelegate订阅者
- (NSArray<id<EXAppDelegateSubscriber>> *)appDelegateSubscribers {
    return @[[NotificationSubscriber new]];
}

@end

3. JS层监听事件

在React Native代码中,通过expo-modules-core的EventEmitter监听Native层发送的事件:

import { EventEmitter } from 'expo-modules-core';
import YourCustomModule from './path/to/your/native/module';

const eventEmitter = new EventEmitter(YourCustomModule);

// 监听远程通知事件
eventEmitter.addListener('RemoteNotificationReceived', (notificationPayload) => {
  console.log('收到远程通知:', notificationPayload);
  // 这里可以处理通知逻辑,比如展示弹窗、更新UI等
});

注意事项

  • 确保App已开启远程通知权限,并在Info.plist中配置remote-notification后台模式
  • Native和JS层的事件名需完全一致
  • 若模块注册表获取失败,检查Native模块是否通过EX_EXPORT_MODULE正确导出,且已完成Expo prebuild模块链接

内容的提问来源于stack exchange,提问作者cip123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:22:37