links: React Native MOC


Native Modules in React Native with Swift

How to expose a Swift Promise?

There are no promises in Swift.

To implement a promise React Native Provides two types RCTPromiseResolveBlock and RCTPromiseRejectBlock and call the internal methods resolve and reject similar to JS Promise.

The resolve method has only 1 argument: the data that you want to resolve with.

The reject method has 3 arguments:

  • An Error Code: something specific to your domain logic
  • An Error Message: rejection reason
  • A NSERROR object: this is usually the error object that you would like to pass.

Let’s export the method to React Native’s Bridge:

// UpdteService.m
 
RCT_EXTERN_METHOD(checkForUpdateAsync:(RCTPromiseResolveBlock)resolve
 rejecter:(RCTPromiseRejectBlock)reject)

Let’s create a function on swift.

@objc(checkForUpdateAsync:rejecter:)
func checkForUpdateAsync(
  _ resolve: RCTPromiseResolveBlock,
  rejecter: RCTPromiseRejectBlock
) -> Void {
  let result: NSMutableDictionary = [:];
  result["isAvailable"] = true;
  resolve(result);
}

tags: react-native native-modules swift

source: