8

In React Native, with the Clipboard, how can I place an image in the Clipboard? The only method provided to set Clipboard content is "setString". Can you not set images or other content than strings?

Michael Steuer
  • 487
  • 5
  • 7

1 Answers1

9

It is possible to bridge native iOS clipboard API and expose the setImage method. To do that you need:

  1. Add native module header file Clipboard.h:

#import "RCTBridgeModule.h"
@interface Clipboard : NSObject <RCTBridgeModule>
@end
  1. Add native module implementation file Clipboard.m. We needed to copy base64 encoded images but you can adjust the code use any other image representation:

#import <UIKit/UIKit.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "Clipboard.h"

@implementation Clipboard

RCT_EXPORT_MODULE(BetterClipboard); // this is how our native module will be named

RCT_EXPORT_METHOD(addBase64Image:(NSString *)base64Image) {
  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  [pasteboard setPersistent:YES];
  
  NSData *imageData = [[NSData alloc]initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];

  [pasteboard setImage:[UIImage imageWithData:imageData]];
}

@end
  1. And then you can use it in your React application:

import { NativeModules } from 'react-native';
   
NativeModules.BetterClipboard.addBase64Image(base64EncodedImage);

Unfortunately, I don't know how to do the same for Android.

Ihor Burlachenko
  • 4,689
  • 1
  • 26
  • 25
  • Way super cool! Is it possible with to get image from clipboard? Did you find out how to do this in android yet? Thanks very much for sharing this!! – Noitidart Apr 07 '18 at 18:28
  • It is possible. I don't want to give you examples of code which I didn't try, just google for "get an image from pasteboard ios". Then you can create React Native API for it using the same approach with native modules. – Ihor Burlachenko Apr 09 '18 at 11:32
  • 1
    Re Android, here is a short explanation of the situation there https://stackoverflow.com/a/39613285/543280 (unless something changed recently). – Ihor Burlachenko Apr 09 '18 at 11:34
  • Thanks Ihor very much! – Noitidart Apr 09 '18 at 14:30