Callback Functions in React Native Swift Modules

2.6k views Asked by At

I'm trying to create a native swift module with a function I can call in my javascript code. Currently I have my module.swift file, my module.m file, and the bridging header.

Here's MyModule.swift:

import Foundation

@objc(MyModule)
class MyModule: NSObject {

  @objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
     let resultsDict = [
     "success" : true
     ];

    callback([NSNull() ,resultsDict])
  }

}

Here's MyModule.m:

#import <Foundation/Foundation.h>

// CalendarManagerBridge.m
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface RCT_EXTERN_MODULE(MyModule, NSObject)

RCT_EXTERN_METHOD(callbackMethod:(RCTResponseSenderBlock)callback)

@end

Here's the bridging header:

#import React/RCTBridgeModule.h

#import React/RCTEventEmitter.h

Finally, here's my call in javascript:

const { MyModule } = require('NativeModules');
MyModule.callbackMethod((err,r) => console.log(r));

The problem is that whenever I run the project, it causes an error:

Exception 'callbackMethod:(RCTResponseSenderBlock)callback is not a recognized Objective-c
 method.' 

However, I can't find anything wrong with the documentation. Could someone please provide some help?

1

There are 1 answers

0
user295145 On

For some reason, we need to write the @objc part differently for methods now.

Change

@objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
 let resultsDict = [
 "success" : true
 ];

callback([NSNull() ,resultsDict])

To

@objc(callbackMethod:)
func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
 let resultsDict = [
 "success" : true
 ];

callback([NSNull() ,resultsDict])