1

Say I have the following Swift class:

@objc(ExampleClass)
  class ExampleClass: NSObject {
  init() {}
  @objc func exampleMethod(_ message: String, _ properties: [String: Any]? = nil) -> Void {}
}

And the following Header:

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

@interface RCT_EXTERN_MODULE(ExampleClass, NSObject)

RCT_EXTERN_METHOD(exampleMethod:(NSString *)name (NSDictionary *)properties)
@end

Which I then call with the following React Native code:

import { NativeModules } from 'react-native'

NativeModules.ExampleClass.exampleMethod('example', {'hello': 'world'})

This results in the following error message:

ExceptionsManager.js:73 Exception 'exampleMethod: is not a recognized Objective-C method.' was thrown while invoking trackEvent on target SegmentTracker with params (
    "example",
        {
        hello = world;
    }
)

While calling it like so:

NativeModules.ExampleClass.exampleMethod('example')

results in:

ExceptionsManager.js:73 Exception 'exampleMethod: is not a recognized Objective-C method.' was thrown while invoking trackEvent on target SegmentTracker with params (
    "example"
)

I have two questions: 1) How do I pass JSON from React Native to Swift? 2) How do I correctly allow for optional parameters in RCT_EXTERN_METHOD? And if that's not possible, how do I handle the case where I would like to sometimes pass a second parameter, and sometimes not?

Abraham P
  • 15,029
  • 13
  • 58
  • 126

3 Answers3

0

You could try with properties of type NSDictionary so that it fits to the interface. It could be similar to:

react-native-bridging-passing-json-to-swift-function

Jeff
  • 840
  • 10
  • 29
Jan F.
  • 1,681
  • 2
  • 15
  • 27
0

You need to use a static method in the swift code @objc static func exampleMethod(...

dondragon2
  • 535
  • 5
  • 15
0

your swift code should be

@objc(ExampleClass)
class ExampleClass: NSObject {
  @objc(exampleMethod:properties:) func exampleMethod(_ message: String, properties: [String: Any]? = nil) -> Void {}
}

And your bridge file should be

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

@interface RCT_EXTERN_MODULE(ExampleClass, NSObject)

RCT_EXTERN_METHOD(exampleMethod:(NSString *)name properties:(NSDictionary *)properties)
@end
dondragon2
  • 535
  • 5
  • 15