본문 바로가기
IT/javascript

react-native iOS 모듈 만들기

by 가능성1g 2024. 11. 22.
반응형

1. 리액트-네이티브 프로젝트 생성

brew install node
brew install watchman
npx react-native@latest init AwesomeProject

 

2. 프로젝트 실행후, iOS 시뮬레이터에서 실행 확인

npm start
# 실행시 meteo 가 실행 되고, i 를 누르면 iOS에뮬레이터가 실행되며 cocoapod 설치 여부 물어봄 설치!

 

3. 네이티브 모듈 생성 ( 파일2개 )

RCTCalendarModule.h

//
//  Header.h
//  AwesomeProject
//
//  Created by 한태종 on 11/22/24.
//

#ifndef RCTCalendarModule_h
#define RCTCalendarModule_h

#import <React/RCTBridgeModule.h>
@interface RCTCalendarModule : NSObject <RCTBridgeModule>
@end

#endif /* RCTCalendarModule_h */

 

RCTCalendarModule.m

//
//  RCTCalendarModule.m
//  AwesomeProject
//
//  Created by 한태종 on 11/22/24.
//

#import <Foundation/Foundation.h>
#import <React/RCTLog.h>

// RCTCalendarModule.m
#import "RCTCalendarModule.h"

@implementation RCTCalendarModule

// To export a module named RCTCalendarModule
// Prefix 빼고 CalendarModule로 JS에서 쓸수 있다.
RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title
                location:(NSString *)location
                myCallback:(RCTResponseSenderBlock)callback)
{
  NSInteger eventId = 1;
  callback(@[@(eventId)]);

  RCTLogInfo(@"Pretending to create an event %@ at %@", title, location);
 }

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getName)
{
return [[UIDevice currentDevice] name];
}



- (NSDictionary *)constantsToExport
{
 return @{ @"DEFAULT_EVENT_NAME": @"New Event" };
}

@end

 

위의 설명처럼 JS 에서 사용할때는 RCT를 빼고 사용하면된다.

 

하지만 구조화를 위해 모듈파일을 별도로 선언하고 typescript를 이용해봤다. 

상위 JS 프로젝트에 아래 파일을 만든다.

NativeCalendarModule.ts

import {NativeModules} from 'react-native';
const {CalendarModule} = NativeModules;
type ConstantsType = {
    DEFAULT_EVENT_NAME: string;
}
interface CalendarInterface {
  createCalendarEvent(name: string, location: string, callback:any): void;
  getConstants(): ConstantsType;
}
export default CalendarModule as CalendarInterface;

 

메인 App.tsx 에서 아래와 같이 사용한다.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React from 'react';
import {
  Button,
  SafeAreaView
} from 'react-native';
import NativeCalendarModule from './NativeCalendarModule';

function App(): React.JSX.Element {
  //const {CalendarModule} = NativeModules;
  const onPress = () => {
    //console.log("aaa")
    NativeCalendarModule.createCalendarEvent(
      'Party',
      '04-12-2020',
      (eventId: any) => {
        console.log(`Created a new event with id ${eventId}`);
      },
    );
    const {DEFAULT_EVENT_NAME} = NativeCalendarModule.getConstants();
    console.log(DEFAULT_EVENT_NAME);
  }
  return (
    <SafeAreaView>
    <Button
      title='Click to invoke your native moudle'
      color="#841584"
      onPress={onPress}
      />
      </SafeAreaView>
  );
}

export default App;

 

 

알아볼점!

네이티브 소스의 RCTLogInfo 함수는 네이티브에서 직접실행할때만 찍힌다. ( react-native 로 DevTool실행할때도 찍혀야 하는데!! )

object-c로 네이티브 개발했는데 swift 도 가능하다고 한다. ( 수정해보자 ) 

반응형