0Pricing
React Native Academy · 강의

Swift로 레거시 네이티브 모듈 작성하기

Objective-C 브리지 파일과 RCTBridgeModule을 준수하는 Swift 클래스를 만들고 RCT_EXPORT_METHOD로 메서드를 노출한 다음 React Native JS에서 호출합니다.

Swift로 레거시 네이티브 모듈 작성하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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로 레거시 네이티브 모듈 작성하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“Swift로 레거시 네이티브 모듈 작성하기”에서 뭘 배우나요?

Objective-C 브리지 파일과 RCTBridgeModule을 준수하는 Swift 클래스를 만들고 RCT_EXPORT_METHOD로 메서드를 노출한 다음 React Native JS에서 호출합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Swift로 레거시 네이티브 모듈 작성하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Kotlin으로 레거시 네이티브 모듈 작성하기
  2. Swift로 레거시 네이티브 모듈 작성하기
  3. JSI를 사용한 Turbo 네이티브 모듈
  4. 네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기
← React Native Academy(으)로 돌아가기