til / Native Module in React Native using Swift
This is a condensed version of the great official documentation for Native Modules in React Native. We’ll be using Swift instead of Objective-C, just because I find it easier. You’ll need a bridging header for this which Xcode should offer to create when adding your first Swift file. For the example, we’ll create a ClipboardModule
to copy strings.
First create a new “Cocoa Touch Class” (ClipboardModule.m
.) This is used as the interface with React Native.
// ClipboardModule.m
#import <React/RCTBridgeModule.h>
// Define the external module with the name ClipboardModule
@interface RCT_EXTERN_MODULE(ClipboardModule, NSObject)
// Export a method called "setString" that takes a string as input
RCT_EXTERN_METHOD(setString:(NSString *)content)
@end
Then, create the Swift class (ClipboardModule.swift
.) This is where we define our code. The @objc
modifiers are important to make sure that the class and the functions can interact with the Objective-C code.
// ClipboardModule.swift
@objc(ClipboardModule)
class ClipboardModule: NSObject {
@objc
func setString(_ content: String) {
// Set the clipboard to our content
UIPasteboard.general.string = content
}
}
Note the leading _
in the arguments, it’s important because the first parameter can’t be named. It’s becomes clearer with multiple parameters or when we need to return values from native code.
To call our method in React land.
// clipboard.ts
import { NativeModules } from "react-native";
const { ClipboardModule } = NativeModules;
// Define an interface to make calling the module more type safe
interface ClipboardInterface {
setString(content: string): void;
}
export default ClipboardModule as ClipboardInterface;
// Other file
import Clipboard from "clipboard.ts";
const copyText = () => {
Clipboard.setString("Hi!");
};
This will all become deprecated when TurboModules become stable, but it should work for the foreseeable future.