0Pricing
React Native Academy · 课时

使用 Swift 编写旧版原生模块

创建 Objective-C 桥接文件和一个遵循 RCTBridgeModule 的 Swift 类,使用 RCT_EXPORT_METHOD 暴露方法,并从 React Native JS 调用它。

使用 Swift 编写旧版原生模块 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

iOS Native Modules Overview

On iOS, legacy native modules expose Swift or Objective-C code to JavaScript through an Objective-C bridge. Even when you write the implementation in Swift, React Native requires an Objective-C bridge header file to register the module because the RN bridge is built in Objective-C. You write a thin .m bridge file alongside your Swift class.

Creating the Swift Module Class

Create a Swift class that conforms to NSObject and is decorated with the @objc attribute so Objective-C can see it. The class implements the RCTBridgeModule protocol. Swift modules also need @objcMembers on the class so all methods are visible to the bridge without individual @objc annotations on each one.

// CalendarModule.swift
import Foundation

@objc(CalendarModule)
class CalendarModule: NSObject {

  @objc
  func createCalendarEvent(
    _ name: String,
    location: String
  ) {
    print('Creating event: \(name) at \(location)')
  }
}

The Objective-C Bridge File

The bridge file is a plain .m file that does no implementation — it only declares your module and its methods using macros. RCT_EXTERN_MODULE registers the class name, and RCT_EXTERN_METHOD declares each exported method with its parameter labels exactly matching the Swift signatures.

// CalendarModuleBridge.m
#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(CalendarModule, NSObject)

RCT_EXTERN_METHOD(
  createCalendarEvent:(NSString *)name
  location:(NSString *)location
)

@end

Exposing the Module Name

React Native identifies your module by the name in RCT_EXTERN_MODULE. On the JavaScript side, this becomes the key on NativeModules. By convention the name matches the Swift class name. If you want a different JavaScript-facing name, you can provide an alias as the second argument to RCT_EXTERN_MODULE, but keeping them the same avoids confusion.

// JavaScript — accessing the iOS module
import { NativeModules } from 'react-native';

const { CalendarModule } = NativeModules;

if (!CalendarModule) {
  console.warn('CalendarModule not found — iOS only?');
} else {
  CalendarModule.createCalendarEvent('Team Lunch', 'Conference Room A');
}

Returning Data with Promises in Swift

Swift native methods that return data use RCTPromiseResolveBlock and RCTPromiseRejectBlock parameters. These are passed in as the last two arguments when declared in the bridge file. Call resolve(value) on success or reject(code, message, error) on failure. On the JS side, await the call as you would any async function.

// Swift method
@objc
func getDeviceModel(
  _ resolve: @escaping RCTPromiseResolveBlock,
  rejecter reject: @escaping RCTPromiseRejectBlock
) {
  let model = UIDevice.current.model
  resolve(model)
}

// Bridge file
RCT_EXTERN_METHOD(
  getDeviceModel:(RCTPromiseResolveBlock)resolve
  rejecter:(RCTPromiseRejectBlock)reject
)

// JavaScript
const model = await CalendarModule.getDeviceModel();

Running on the Main Thread

Native module methods run on a background serial queue by default. If your method touches UIKit (which requires the main thread), you must dispatch to the main queue. You can override the static method requiresMainQueueSetup() to return true if the module needs to be initialized on the main thread from the start.

@objc
static func requiresMainQueueSetup() -> Bool {
  return true // init on main thread
}

@objc
func openAlert(_ message: String) {
  DispatchQueue.main.async {
    let alert = UIAlertController(
      title: 'Alert',
      message: message,
      preferredStyle: .alert
    )
    alert.addAction(UIAlertAction(title: 'OK', style: .default))
    UIApplication.shared.keyWindow?.rootViewController?
      .present(alert, animated: true)
  }
}

Exporting Constants to JavaScript

Like Android, iOS native modules can expose constants via the constantsToExport() method. Return a dictionary of values that React Native serializes and attaches to the module object in JavaScript at startup. Constants are synchronous and zero-cost to read after initialization.

// Swift
@objc
func constantsToExport() -> [String: Any]! {
  return [
    'PLATFORM': 'ios',
    'OS_VERSION': UIDevice.current.systemVersion,
    'IS_PAD': UIDevice.current.userInterfaceIdiom == .pad
  ]
}

// Bridge file (add inside the interface)
RCT_EXPORT_MODULE()

// JavaScript
const { PLATFORM, IS_PAD } = NativeModules.CalendarModule;
console.log(PLATFORM, IS_PAD);

Sending Events to JavaScript

To push data from native to JavaScript proactively, your Swift module should extend RCTEventEmitter instead of NSObject. Override supportedEvents() to list event names, and call sendEvent(withName:body:) to emit. On the JS side, use NativeEventEmitter to subscribe to the events.

// Swift
@objc(LocationModule)
class LocationModule: RCTEventEmitter {
  override func supportedEvents() -> [String]! {
    return ['onLocationUpdate']
  }

  func startTracking() {
    sendEvent(withName: 'onLocationUpdate',
              body: ['lat': 37.7749, 'lng': -122.4194])
  }
}

// JavaScript
import { NativeModules, NativeEventEmitter } from 'react-native';
const emitter = new NativeEventEmitter(NativeModules.LocationModule);
const sub = emitter.addListener('onLocationUpdate', (loc) => {
  console.log(loc.lat, loc.lng);
});
// cleanup: sub.remove();

Cross-Platform Module Wrapper

When your module only exists on one platform, guard calls with Platform.OS in your wrapper file to avoid runtime crashes on the other platform. A common pattern is to export a no-op stub on unsupported platforms so calling code never needs to check Platform.OS itself.

// CalendarModule.js
import { NativeModules, Platform } from 'react-native';

const { CalendarModule: NativeCalendar } = NativeModules;

export const CalendarModule = {
  createEvent: (name, location) => {
    if (Platform.OS === 'ios' && NativeCalendar) {
      NativeCalendar.createCalendarEvent(name, location);
    } else {
      console.warn('CalendarModule not available on', Platform.OS);
    }
  }
};

Handling Bridging Header for Mixed Projects

When you add Swift files to an Objective-C project (the default for older React Native), Xcode asks to create a bridging header. This file imports the Objective-C headers that Swift needs to see. You typically import React/RCTBridgeModule.h, React/RCTEventEmitter.h, and any other RN headers your Swift code references. Without this file, Swift cannot see the RCT types.

// YourApp-Bridging-Header.h
// Auto-created by Xcode when adding first Swift file

#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTLog.h>
#import <React/RCTUtils.h>

Testing the Native Module End-to-End

After writing your Swift class and bridge file, rebuild the app from Xcode (not just Metro) because native code changes require a full native build. Open the iOS Simulator, trigger the JS code that calls your module, and use console.log or Xcode's console to verify the native side executes. Xcode's debugger can set breakpoints in Swift code while the React Native app runs.

// Quick integration test in a component
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { CalendarModule } from './CalendarModule';

export function TestScreen() {
  useEffect(() => {
    CalendarModule.createEvent('Standup', 'Zoom')
      .then((result) => console.log('Event created:', result))
      .catch((err) => console.error('Error:', err));
  }, []);

  return <View><Text>Native Module Test</Text></View>;
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: how to create a Swift class conforming to RCTBridgeModule, write an Objective-C bridge file with RCT_EXTERN_MODULE and RCT_EXTERN_METHOD, and return async data using RCTPromiseResolveBlock and RCTPromiseRejectBlock. You also saw how to emit events with RCTEventEmitter. Next up we explore the modern Turbo Native Module architecture with JSI.

常见问题解答

「使用 Swift 编写旧版原生模块」课时是免费的吗?

是的 — 「使用 Swift 编写旧版原生模块」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。

「使用 Swift 编写旧版原生模块」这节课中我会学到什么?

创建 Objective-C 桥接文件和一个遵循 RCTBridgeModule 的 Swift 类,使用 RCT_EXPORT_METHOD 暴露方法,并从 React Native JS 调用它。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Native Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 Swift 编写旧版原生模块」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Native Academy 课中编写并运行代码吗?

能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Kotlin 编写旧版原生模块
  2. 使用 Swift 编写旧版原生模块
  3. 使用 JSI 编写 Turbo 原生模块
  4. 来自原生代码的异步回调、Promise 与事件
← 返回 React Native Academy