Create a React Native custom module (with Swift)

Here is a quick and dirty example of how one can expose a custom module to React Native using Swift.

Product-Bridging-Header.h – Bridge header file

#import "RCTBridgeModule.h"

MySwiftThingy.m – Register Swift code with the React Native Bridge

#import "RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(MySwiftThingy, NSObject)

RCT_EXTERN_METHOD(callbackMethod:(RCTResponseSenderBlock)callback)
RCT_EXTERN_METHOD(simpleMethod:(NSString *)message)

@end

MySwiftThingy.swift – Custom Swift component

import Foundation

@objc(MySwiftThingy)
class MySwiftThingy: NSObject {
  
  @objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
    let resultsDict = [
      "success" : true
    ];
    
    callback([NSNull() ,resultsDict])
  }
  
  @objc func simpleMethod(message: String!) {
    print("\(message)")
  }
}

Call it from JavaScript:

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

You may also like...

2 Responses

  1. User says:

    Thanks for this.

    Any chance you know how to set the constructor ( init() ) in Swift?
    I am getting the following error after launching the app:
    fatal error: use of unimplemented initializer ‘init()’

    Thanks.

  2. Coty Embry says:

    How do you call the callback from another class outside of the MySwiftThingy.swift file? I want to be able to create an instance of one of my custom classes and whenever I want to, thats probably not possible… meaning the callback is only available to call when first initiated by javascript.. I want to be able to call javascript when first initiated by swift and have been trying for about 3 days now and have not succeeded. Im having trouble storing the callbacks and also sending the event because the bridge ends up not getting set. I even created this question for help: http://stackoverflow.com/questions/43246051/send-event-to-js-from-swift-or-objective-c

Leave a Reply