how do I pass image data to a native module in React Native?

3.4k Views Asked by At

In my class that implements the RCTBridgeModule protocol in Xcode, I am trying to write an RCT_EXPORT_MEATHOD that I can expose to React Native code to consume image data. Currently, I can write an image to disk in React Native, and then pass the path through to the native method, but I'm wondering if there is a better technique to pass image data directly for better performance?

So instead of this:

RCT_EXPORT_METHOD(scanImage:(NSString *)path) {
  UIImage *sampleImage = [[UIImage alloc] initWithContentsOfFile:path];  
  [self processImage: UIImage];
}

Something more like this:

RCT_EXPORT_METHOD(scanImage:(NSData *)imageData) {
  [self processImageWithData: imageData];
}
2

There are 2 best solutions below

1
Aleksandras On

You can use [RCTConvert UIImage:icon] method from #import <React/RCTConvert.h>

You need to specify "schema" as "data". For more details look at the source code bellow: https://github.com/facebook/react-native/blob/master/React/Base/RCTConvert.m#L762

0
Dotan Simha On

For me, this works:

  NSURL *url = [NSURL URLWithString:[imagePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
  UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];

imagePath is NSString comes from the react-native bridge (using react-native-image-picker's response - response.uri).