react native iOS bridge 实践

190 阅读1分钟

最近试着能否通过 ai 来实现自己以前无法完成的工作,比如 react native 使用 bridge 调用 iOS 原生功能,现记录下工作流程,环境为 xcode 16

创建 h 和 m 文件

以显示 Toast 为例,代码均由 ai 生成

#import <React/RCTBridgeModule.h>

@interface ToastModule : NSObject <RCTBridgeModule>
@end
#import "ToastModule.h"
#import <UIKit/UIKit.h>

@implementation ToastModule

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(showToast:(NSString *)message duration:(double)duration) {
  dispatch_async(dispatch_get_main_queue(), ^{
    UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [rootViewController presentViewController:alert animated:YES completion:nil];

    // 在指定时间后关闭
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });
  });
}

@end

拖动文件到 xcode

上述两个文件创建完后,拖动到 xcode,通常放在 iOS 目录即根目录下,会跳出一个弹框,标题为 Choose options for adding these files,勾选需要的 Targets,点击 finish,然后可以发现 project.pbxproj 有一些代码的变动

创建 Header 文件

文件建立后,还需要 Header 文件来引入上述的桥接文件,在 Xcode 中,选择 File -> New -> File from Template... ,然后选择 Header File,点击 Next,同样需要我们设置 Targets,勾选需要的,自动生成了 Header.h 文件

#ifndef Header_h
#define Header_h

#endif /* Header_h */

这时候,引入我们需要的

#ifndef Header_h
#define Header_h

#import "ToastModule.h"

#endif /* Header_h */

react native 中调用

以下是调用的代码,能成功显示 Toast

import { NativeModules } from 'react-native';
const { ToastModule } = NativeModules;

const showToast = (message, duration) => {
    ToastModule.showToast(message, duration);
};