AirUp
AirUp

Reputation: 446

React Native Swift callback

I would like to send a String to a Swift-implemented module from React Native and then just get a String result as a callback from the native module for further use.

Here's what i've got:

//HelloWorldModule.m

#import "RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(HelloWorldModule, NSObject)

RCT_EXTERN_METHOD(sayHelloWorld:(NSString *)name callback:(RCTResponseSenderBlock *)successCallback)

@end

Alongside the Swift implementation:

//  HelloWorldModule.swift

import Foundation
import UIKit
import AVFoundation

@objc(HelloWorldModule)
class HelloWorldModule: NSObject {

  @objc func sayHelloWorld(name: String,  callback successCallback: RCTResponseSenderBlock) {
    NSLog("Log from Swift: \(name)")
    successCallback([name])
  }
}

and finally whatever goes into the ReactNative part:

// requiring the Swift module in React Native
var HelloWorldModule = require('react-native').NativeModules.HelloWorldModule;

...

// using it somewhere in the render function

render: function() {
       return (
        <Text>
          Hello World Module answers: {this.hwmExt("Jadzia Dax")}
        </Text>
       );
},

hwmExt: function(name) {
    return HelloWorldModule.sayHelloWorld(name, function(result) {
       var hwAnswer = "swiftCB: " + result;
       console.log(hwAnswer);
       return hwAnswer;
    });
}

The line console.log(hwAnswer); prints out what I expect it to be swiftCB: Jadzia Dax but the result is not being passed over? Did I do something wrong in the method definition in Swift as I always get undefined? Somehow got blind over this problem :/ React Native Swift module callbacks are unfortunately not covered in the RN docs, too.

Upvotes: 9

Views: 12545

Answers (1)

cmd
cmd

Reputation: 11841

The RCTResponseSenderBlock callback follows Node.js error first style i.e. the first callback param holds error and the second param holds result.

In your example, you are returning a value for error, and no value result, hence undefined. You should return NSNull as the error (first) parameter, and name as the second param e.g. [NSNUll(), name].

This short blog post shows exactly how to do this using Swift and React Native. In the blog post, see line 11 in MySwiftThingy.swift.

Upvotes: 13

Related Questions