2

I am creating native module using create-react-native-module with swift. After that I have followed react native official documentation for iOS setup. doc link:: https://facebook.github.io/react-native/docs/native-modules-ios

I have created create-react-native-module with example. I am just adding simple function with returning string "Hello World" inside my native module.

My 'CustomModule-Bridging-Header.h'::

#import <React/RCTBridgeModule.h>

My 'CustomModule.m'::

#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(CustomModule, NSObject)

RCT_EXTERN_METHOD(sampleMethod)

+ (BOOL) requiresMainQueueSetup {
  return YES;
}

@end

My 'CustomModule.swift':

import Foundation

@objc(CustomModule)
class CustomModule: NSObject {
  @objc(sampleMethod)
  func sampleMethod() -> String {
      return "Hello World"
  }
}

After making these changes to native module I have installed dependencies again inside example. Now my App.js is look like::

import React, { Component } from 'react';
import { Platform, Text, View } from 'react-native';
import CustomModule from 'react-native-custom-module';

export default class App extends Component {
    state = {
        message: '--'
    };

    async componentDidMount() {
        const msg = await CustomModule.sampleMethod();
        console.log('javascript calling msg::', msg);
        this.setState({
            message: msg
        });
    }
    render() {
        return (
            <View>
                <Text>CustomModule example☆</Text>
                <Text>{this.state.message}</Text>
            </View>
        );
    }
}

Here I am getting "msg" value as undefined. Please help!

1
  • Hi @Archana Sharma how did you sort out the "<React/RCTBridgeModule.h>" file not found issue when you first created the react-native-module from the command line. I am getting the above error. Could you please let me know ? Commented Apr 17, 2020 at 9:41

1 Answer 1

2

You need to use promise or callback to return value from the native function. Simply returning value does not work.

Example using promise:

CustomModule.swift

@objc
func sampleMethod(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
  resolve("Hello World")
}

CustomModule.m

RCT_EXTERN_METHOD(sampleMethod: (RCTPromiseResolveBlock)resolve rejecter: (RCTPromiseRejectBlock)reject)
Sign up to request clarification or add additional context in comments.

1 Comment

how to resolve a Query? You have mentioned resolve("Hello World"). What if I have a HKStatisticsQuery and I need to read this in my JS file. How can I resolve this???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.