Skip to content

Instantly share code, notes, and snippets.

@shirakaba
Last active June 15, 2018 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirakaba/ac750aa629f0e41e4df525063d1955e2 to your computer and use it in GitHub Desktop.
Save shirakaba/ac750aa629f0e41e4df525063d1955e2 to your computer and use it in GitHub Desktop.
Using Swift in React Native

Bridging header

Purpose

While you can't import Objective-C headers directly in Swift files, you can import them all into a bridging header file, which will subsequently be exposed to your Swift environment throughout the project.

Thus, you should write into the bridging header the union of all headers you'll be referring to (e.g. due to invoking APIs or asserting types) in your Swift code.

For a React Native project, the fundamental headers you'll need come from the React static library. If you call upon any native modules, you'll need to import their headers, too.

Content

/* Here are all the headers from the React static library that I'm aware of: */
#import <React/RCTBundleURLProvider.h>
#import <React/RCTJavaScriptLoader.h>
#import <React/RCTLinkingManager.h>
#import <React/RCTRootView.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTUIManager.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>

/* If you import from any RN native modules from node_modules, again specify
 * them in the following format:
 *
 * <${static_library_name}/${header}>
 *
 * You can determine the static library name by opening the relevant module's
 * .xcodeproj and, from its Project Navigator screen, viewing the names of all
 * its buildable targets. e.g., from the RCTWKWebView project:
 */
// #import <RCTWKWebView-macos/RCTWKWebView.h>

Native modules

(to-do)

Exposing native code to React Native relies heavily upon pre-processor macros, which are unfortunately only sufficiently supported in Obj-C. Thus, it is unavoidable to write at least the method signatures in Obj-C. However, the implementation for your methods can be written entirely in Swift.

// Use RCT_EXPORT_MODULE() to expose a class to React Native whose implementation is writen (in the same file) in Obj-C.
// Use RCT_EXPORT_METHOD() to expose a method to React Native whose implementation is writen (in the same file) in Obj-C.

// Use RCT_EXTERN_MODULE() to expose a class to React Native whose implementation is writen (in an external file) in Swift.
// Use RCT_EXTERN_METHOD() to expose a method to React Native whose implementation is written (in an external file) in Swift.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment