2

Trying to bubble a function I made in Swift file to the main App.tsx

HelloWorld.swift

@objc(HelloWorldModule)
class HelloWorldModule: NSObject {
  @objc
  func ShowMessage()->Void
  {
    print("hello world")
  }
}

HelloWorld.m

#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(HelloWorldModule, NSObject)
RCT_EXTERN_METHOD(ShowMessage)
@end

App.tsx. -- the main app from react native


import React, { useEffect, useRef, useState } from 'react';
import { Alert, Button, Image, NativeModules } from 'react-native';
import styled from 'styled-components/native';


console.log(NativeModules.HelloWorldModule);
NativeModules.HelloWorldModule.ShowMessage();

Goal: Trying to get the terminal log to output "hello world" from App.tsx

Actual Output:

 LOG  {"ShowMessage": [Function nonPromiseMethodWrapper], "getConstants": [Function anonymous]}
 WARN  Module HelloWorldModule requires main queue setup since it overrides `init` but doesn't 
implement `requiresMainQueueSetup`. In a future release React Native will default to initializing 
all native modules on a background thread unless explicitly opted-out of.
bombombs
  • 593
  • 1
  • 13
  • In the example from docs here: https://reactnative.dev/docs/native-modules-ios it's using RCT_EXPORT_MODULE macro. Why did you use your own interface in HelloWordl.m and what it does actually? Am I missing something? – omer.ersoy Jun 23 '22 at 07:58
  • @omer.ersoy I am trying to run the function ShowMessage that I created in HelloWorld.swift in App.tsx. My goal is to get "hello world" as an output from the terminal log – bombombs Jun 23 '22 at 13:09

1 Answers1

0

For future reference:

There are two issues at play here.

1. Warning Issue

The warning you're seeing is mentioned in the current react-native's docs:

For iOS, if you override constantsToExport() then you should also implement + requiresMainQueueSetup to let React Native know if your module needs to be initialized on the main thread, before any JavaScript code executes. Otherwise you will see a warning that in the future your module may be initialized on a background thread unless you explicitly opt out with + requiresMainQueueSetup:.

Implementing the following method on HelloWorldModule will get rid of the warning:

@objc
static func requiresMainQueueSetup() -> Bool {
  return true // or false; see docs
}
2. Incorrect terminal output

You can use promises in order to pass data from iOS to react-native. In your case, you'd need to change the implementation of ShowMessage() to:

@objc
func ShowMessage(_ resolve: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) -> Void
{
  resolve("hello world")
}

Then, on the react-native side, you can read the message with:

NativeModules.HelloWorldModule.ShowMessage()
  .then(message => console.log(message))
andersonvom
  • 11,701
  • 4
  • 35
  • 40