RN iOS混合开发调用AppDelegate自定义initSdk方法报错怎么解决
问题解决步骤
1. 修正initSDK方法的Objective-C语法错误
你当前定义的initSDK方法签名不符合Objective-C语法规范,同时注意原有代码中遗漏了entity变量的初始化,修正后的实现如下:
// AppDelegate.m 中的方法实现 - (void)initSDKWithLaunchOptions:(NSDictionary *)launchOptions { // 原有初始化代码 [UNUserNotificationCenter currentNotificationCenter].delegate = self; // 补上entity的初始化代码 UMessageRegisterEntity *entity = [[UMessageRegisterEntity alloc] init]; [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { // 授权成功逻辑 }else{ // 授权失败逻辑 } }]; }
2. 在头文件中对外暴露方法
Objective-C中要让其他类调用当前类的方法,必须在.h头文件的接口声明中暴露方法定义,修改AppDelegate.h如下:
#import <React/RCTBridgeDelegate.h> #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate> + (AppDelegate *)sharedAppDel; @property(nonatomic, strong) UIWindow *window; // 新增下面这行暴露初始化方法 @property (nonatomic, strong) NSDictionary *launchOptions; - (void)initSDKWithLaunchOptions:(NSDictionary *)launchOptions; @end
同时在原有的didFinishLaunchingWithOptions方法开头存储启动参数:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.launchOptions = launchOptions; // 原有其他代码 }
3. 修正实例获取与调用逻辑
你自己实现的sharedAppDel方法存在逻辑错误,自行alloc init生成的AppDelegate实例不是当前App运行时的系统实例,会导致功能异常,有两种修正方案:
方案一:使用系统提供的AppDelegate获取方式(推荐)
直接调用系统接口获取当前运行的AppDelegate实例,不需要自行实现单例方法:
// SDKModule.m 顶部先导入头文件 #import "AppDelegate.h" // 调用处代码 AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDel initSDKWithLaunchOptions:appDel.launchOptions];
方案二:修正自定义单例方法
如果要保留自定义的sharedAppDel方法,修改实现如下:
// AppDelegate.m 中的单例方法 + (AppDelegate *)sharedAppDel { return (AppDelegate *)[UIApplication sharedApplication].delegate; }
调用代码如下:
[[AppDelegate sharedAppDel] initSDKWithLaunchOptions:[AppDelegate sharedAppDel].launchOptions];
注意事项
- Objective-C方法名大小写敏感,定义的方法名和调用的方法名大小写必须完全一致,否则会报找不到 selector 错误
- 所有调用AppDelegate方法的类,必须在文件顶部导入
AppDelegate.h头文件
内容的提问来源于stack exchange,提问作者C.Lu
相关产品推荐
相关产品推荐

