mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
212 lines
70 KiB
HTML
212 lines
70 KiB
HTML
<!DOCTYPE html><html><head><title>Native Modules</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport" content="width=device-width"><meta property="fb:app_id" content="1677033832619985"><meta property="fb:admins" content="121800083"><meta property="og:site_name" content="React Native"><meta property="og:title" content="Native Modules"><meta property="og:url" content="https://facebook.github.io/react-native/index.html"><meta property="og:image" content="https://facebook.github.io/react-native/img/opengraph.png"><meta property="og:description" content="A framework for building native apps using React"><meta name="twitter:site" content="@reactnative"><meta name="twitter:card" content="summary_large_image"><meta property="og:type" content="website"><base href="/react-native/"><link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css"><link rel="shortcut icon" href="img/favicon.png?2"><link rel="stylesheet" href="css/react-native.css"><link rel="alternate" type="application/rss+xml" title="React Native Blog" href="https://facebook.github.io/react-native/blog/feed.xml"><link href="//cdn-images.mailchimp.com/embedcode/horizontal-slim-10_7.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="//use.typekit.net/vqa1hcx.js"></script><script type="text/javascript">try{Typekit.load();}catch(e){}</script></head><body><script>window.fbAsyncInit = function() {FB.init({appId:'1677033832619985',xfbml:true,version:'v2.7'});};(function(d, s, id){var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); js.id = id;js.src = '//connect.facebook.net/en_US/sdk.js';fjs.parentNode.insertBefore(js, fjs);}(document, 'script','facebook-jssdk'));</script><script>window.twttr=(function(d,s, id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))return t;js=d.createElement(s);js.id=id;js.src='https://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js, fjs);t._e = [];t.ready = function(f) {t._e.push(f);};return t;}(document, 'script', 'twitter-wjs'));</script><div class="container"><div class="nav-main"><div class="wrap"><a class="nav-home" href=""><img src="img/header_logo.png">React Native</a><a class="nav-version" href="/react-native/versions.html">0.45</a><div class="nav-site-wrapper"><ul class="nav-site nav-site-internal"><li><a href="docs/getting-started.html" class="active" data-target=".nav-docs">Docs</a></li><li><a href="/react-native/support.html" class="">Help</a></li><li><a href="/react-native/showcase.html" class="">Showcase</a></li><li><a href="/react-native/blog/" class="">Blog</a></li></ul><div class="algolia-search-wrapper"><input id="algolia-doc-search" tabindex="0" type="text" placeholder="Search docs..."></div><ul class="nav-site nav-site-external"><li><a href="https://github.com/facebook/react-native" class="">GitHub</a></li><li><a href="http://facebook.github.io/react" class="">React</a></li></ul></div></div></div><section class="content wrap documentationContent"><div class="nav-docs"><div class="nav-docs-viewport"><div class="nav-docs-section"><h3>The Basics</h3><ul><li><a style="margin-left:10px;" class="" href="docs/getting-started.html">Getting Started</a></li><li><a style="margin-left:10px;" class="" href="docs/tutorial.html">Tutorial</a></li><li><a style="margin-left:10px;" class="" href="docs/props.html">Props</a></li><li><a style="margin-left:10px;" class="" href="docs/state.html">State</a></li><li><a style="margin-left:10px;" class="" href="docs/style.html">Style</a></li><li><a style="margin-left:10px;" class="" href="docs/height-and-width.html">Height and Width</a></li><li><a style="margin-left:10px;" class="" href="docs/flexbox.html">Layout with Flexbox</a></li><li><a style="margin-left:10px;" class="" href="docs/handling-text-input.html">Handling Text Input</a></li><li><a style="margin-left:10px;" class="" href="docs/using-a-scrollview.html">Using a ScrollView</a></li><li><a style="margin-left:10px;" class="" href="docs/using-a-listview.html">Using List Views</a></li><li><a style="margin-left:10px;" class="" href="docs/network.html">Networking</a></li><li><a style="margin-left:10px;" class="" href="docs/more-resources.html">More Resources</a></li></ul></div><div class="nav-docs-section"><h3>Guides</h3><ul><li><a style="margin-left:10px;" class="" href="docs/handling-touches.html">Handling Touches</a></li><li><a style="margin-left:10px;" class="" href="docs/animations.html">Animations</a></li><li><a style="margin-left:10px;" class="" href="docs/navigation.html">Navigation</a></li><li><a style="margin-left:10px;" class="" href="docs/images.html">Images</a></li><li><a style="margin-left:10px;" class="" href="docs/colors.html">Colors</a></li><li><a style="margin-left:10px;" class="" href="docs/platform-specific-code.html">Platform Specific Code</a></li><li><a style="margin-left:10px;" class="" href="docs/debugging.html">Debugging</a></li><li><a style="margin-left:10px;" class="" href="docs/accessibility.html">Accessibility</a></li><li><a style="margin-left:10px;" class="" href="docs/timers.html">Timers</a></li><li><a style="margin-left:10px;" class="" href="docs/javascript-environment.html">JavaScript Environment</a></li><li><a style="margin-left:10px;" class="" href="docs/direct-manipulation.html">Direct Manipulation</a></li><li><a style="margin-left:10px;" class="" href="docs/performance.html">Performance</a></li><li><a style="margin-left:10px;" class="" href="docs/gesture-responder-system.html">Gesture Responder System</a></li><li><a style="margin-left:10px;" class="" href="docs/testing.html">Testing</a></li><li><a style="margin-left:10px;" class="" href="docs/understanding-cli.html">Understanding the CLI</a></li><li><a style="margin-left:10px;" class="" href="docs/integration-with-existing-apps.html">Integration With Existing Apps</a></li><li><a style="margin-left:10px;" class="" href="docs/running-on-device.html">Running On Device</a></li><li><a style="margin-left:10px;" class="" href="docs/upgrading.html">Upgrading to new React Native versions</a></li></ul></div><div class="nav-docs-section"><h3>Guides (iOS)</h3><ul><li><a style="margin-left:10px;" class="active" href="docs/native-modules-ios.html">Native Modules</a></li><li><a style="margin-left:10px;" class="" href="docs/native-components-ios.html">Native UI Components</a></li><li><a style="margin-left:10px;" class="" href="docs/linking-libraries-ios.html">Linking Libraries</a></li><li><a style="margin-left:10px;" class="" href="docs/running-on-simulator-ios.html">Running On Simulator</a></li><li><a style="margin-left:10px;" class="" href="docs/communication-ios.html">Communication between native and React Native</a></li></ul></div><div class="nav-docs-section"><h3>Guides (Apple TV)</h3><ul><li><a style="margin-left:10px;" class="" href="docs/building-for-apple-tv.html">Building For Apple TV</a></li></ul></div><div class="nav-docs-section"><h3>Guides (Android)</h3><ul><li><a style="margin-left:10px;" class="" href="docs/native-modules-android.html">Native Modules</a></li><li><a style="margin-left:10px;" class="" href="docs/native-components-android.html">Native UI Components</a></li><li><a style="margin-left:10px;" class="" href="docs/headless-js-android.html">Headless JS</a></li><li><a style="margin-left:10px;" class="" href="docs/signed-apk-android.html">Generating Signed APK</a></li><li><a style="margin-left:10px;" class="" href="docs/android-building-from-source.html">Building React Native from source</a></li></ul></div><div class="nav-docs-section"><h3>components</h3><ul><li><a style="margin-left:10px;" class="" href="docs/activityindicator.html">ActivityIndicator</a></li><li><a style="margin-left:10px;" class="" href="docs/button.html">Button</a></li><li><a style="margin-left:10px;" class="" href="docs/datepickerios.html">DatePickerIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/drawerlayoutandroid.html">DrawerLayoutAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/flatlist.html">FlatList</a></li><li><a style="margin-left:10px;" class="" href="docs/image.html">Image</a></li><li><a style="margin-left:10px;" class="" href="docs/keyboardavoidingview.html">KeyboardAvoidingView</a></li><li><a style="margin-left:10px;" class="" href="docs/listview.html">ListView</a></li><li><a style="margin-left:10px;" class="" href="docs/modal.html">Modal</a></li><li><a style="margin-left:10px;" class="" href="docs/navigatorios.html">NavigatorIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/picker.html">Picker</a></li><li><a style="margin-left:10px;" class="" href="docs/pickerios.html">PickerIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/progressbarandroid.html">ProgressBarAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/progressviewios.html">ProgressViewIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/refreshcontrol.html">RefreshControl</a></li><li><a style="margin-left:10px;" class="" href="docs/scrollview.html">ScrollView</a></li><li><a style="margin-left:10px;" class="" href="docs/sectionlist.html">SectionList</a></li><li><a style="margin-left:10px;" class="" href="docs/segmentedcontrolios.html">SegmentedControlIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/slider.html">Slider</a></li><li><a style="margin-left:10px;" class="" href="docs/snapshotviewios.html">SnapshotViewIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/statusbar.html">StatusBar</a></li><li><a style="margin-left:10px;" class="" href="docs/switch.html">Switch</a></li><li><a style="margin-left:10px;" class="" href="docs/tabbarios.html">TabBarIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/tabbarios-item.html">TabBarIOS.Item</a></li><li><a style="margin-left:10px;" class="" href="docs/text.html">Text</a></li><li><a style="margin-left:10px;" class="" href="docs/textinput.html">TextInput</a></li><li><a style="margin-left:10px;" class="" href="docs/toolbarandroid.html">ToolbarAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/touchablehighlight.html">TouchableHighlight</a></li><li><a style="margin-left:10px;" class="" href="docs/touchablenativefeedback.html">TouchableNativeFeedback</a></li><li><a style="margin-left:10px;" class="" href="docs/touchableopacity.html">TouchableOpacity</a></li><li><a style="margin-left:10px;" class="" href="docs/touchablewithoutfeedback.html">TouchableWithoutFeedback</a></li><li><a style="margin-left:10px;" class="" href="docs/view.html">View</a></li><li><a style="margin-left:10px;" class="" href="docs/viewpagerandroid.html">ViewPagerAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/virtualizedlist.html">VirtualizedList</a></li><li><a style="margin-left:10px;" class="" href="docs/webview.html">WebView</a></li></ul></div><div class="nav-docs-section"><h3>APIs</h3><ul><li><a style="margin-left:10px;" class="" href="docs/accessibilityinfo.html">AccessibilityInfo</a></li><li><a style="margin-left:10px;" class="" href="docs/actionsheetios.html">ActionSheetIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/adsupportios.html">AdSupportIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/alert.html">Alert</a></li><li><a style="margin-left:10px;" class="" href="docs/alertios.html">AlertIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/animated.html">Animated</a></li><li><a style="margin-left:10px;" class="" href="docs/appregistry.html">AppRegistry</a></li><li><a style="margin-left:10px;" class="" href="docs/appstate.html">AppState</a></li><li><a style="margin-left:10px;" class="" href="docs/asyncstorage.html">AsyncStorage</a></li><li><a style="margin-left:10px;" class="" href="docs/backandroid.html">BackAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/backhandler.html">BackHandler</a></li><li><a style="margin-left:10px;" class="" href="docs/cameraroll.html">CameraRoll</a></li><li><a style="margin-left:10px;" class="" href="docs/clipboard.html">Clipboard</a></li><li><a style="margin-left:10px;" class="" href="docs/datepickerandroid.html">DatePickerAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/dimensions.html">Dimensions</a></li><li><a style="margin-left:10px;" class="" href="docs/easing.html">Easing</a></li><li><a style="margin-left:10px;" class="" href="docs/geolocation.html">Geolocation</a></li><li><a style="margin-left:10px;" class="" href="docs/imageeditor.html">ImageEditor</a></li><li><a style="margin-left:10px;" class="" href="docs/imagepickerios.html">ImagePickerIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/imagestore.html">ImageStore</a></li><li><a style="margin-left:10px;" class="" href="docs/interactionmanager.html">InteractionManager</a></li><li><a style="margin-left:10px;" class="" href="docs/keyboard.html">Keyboard</a></li><li><a style="margin-left:10px;" class="" href="docs/layoutanimation.html">LayoutAnimation</a></li><li><a style="margin-left:10px;" class="" href="docs/linking.html">Linking</a></li><li><a style="margin-left:10px;" class="" href="docs/nativemethodsmixin.html">NativeMethodsMixin</a></li><li><a style="margin-left:10px;" class="" href="docs/netinfo.html">NetInfo</a></li><li><a style="margin-left:10px;" class="" href="docs/panresponder.html">PanResponder</a></li><li><a style="margin-left:10px;" class="" href="docs/permissionsandroid.html">PermissionsAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/pixelratio.html">PixelRatio</a></li><li><a style="margin-left:10px;" class="" href="docs/pushnotificationios.html">PushNotificationIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/settings.html">Settings</a></li><li><a style="margin-left:10px;" class="" href="docs/share.html">Share</a></li><li><a style="margin-left:10px;" class="" href="docs/statusbarios.html">StatusBarIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/stylesheet.html">StyleSheet</a></li><li><a style="margin-left:10px;" class="" href="docs/systrace.html">Systrace</a></li><li><a style="margin-left:10px;" class="" href="docs/timepickerandroid.html">TimePickerAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/toastandroid.html">ToastAndroid</a></li><li><a style="margin-left:10px;" class="" href="docs/vibration.html">Vibration</a></li><li><a style="margin-left:10px;" class="" href="docs/vibrationios.html">VibrationIOS</a></li><li><a style="margin-left:10px;" class="" href="docs/layout-props.html">Layout Props</a></li><li><a style="margin-left:10px;" class="" href="docs/shadow-props.html">Shadow Props</a></li></ul></div></div></div><div class="inner-content"><a id="content"></a><h1><a class="anchor" name="native-modules"></a>Native Modules <a class="hash-link" href="docs/native-modules-ios.html#native-modules">#</a></h1><div class="banner-crna-ejected"><h3>Project with Native Code Required</h3><p>This page only applies to projects made with <code>react-native init</code> or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the <a href="https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md" target="_blank">guide</a> on the Create React Native App repository.</p></div><div><p>Sometimes an app needs access to platform API, and React Native doesn't have a corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift or C++ code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.</p><p>We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.</p><p>This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C or Swift and core libraries (Foundation, UIKit).</p><h2><a class="anchor" name="ios-calendar-module-example"></a>iOS Calendar Module Example <a class="hash-link" href="docs/native-modules-ios.html#ios-calendar-module-example">#</a></h2><p>This guide will use the <a href="https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/EventKitProgGuide/Introduction/Introduction.html" target="_blank">iOS Calendar API</a> example. Let's say we would like to be able to access the iOS calendar from JavaScript.</p><p>A native module is just an Objective-C class that implements the <code>RCTBridgeModule</code> protocol. If you are wondering, RCT is an abbreviation of ReaCT.</p><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManager.h
|
|
</span>#import <React<span class="token operator">/</span>RCTBridgeModule<span class="token punctuation">.</span>h<span class="token operator">></span>
|
|
|
|
@interface <span class="token class-name">CalendarManager</span> <span class="token punctuation">:</span> NSObject <RCTBridgeModule<span class="token operator">></span>
|
|
@end</div><p>In addition to implementing the <code>RCTBridgeModule</code> protocol, your class must also include the <code>RCT_EXPORT_MODULE()</code> macro. This takes an optional argument that specifies the name that the module will be accessible as in your JavaScript code (more on this later). If you do not specify a name, the JavaScript module name will match the Objective-C class name.</p><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManager.m
|
|
</span>@implementation CalendarManager
|
|
<span class="token comment" spellcheck="true">
|
|
// To export a module named CalendarManager
|
|
</span><span class="token function">RCT_EXPORT_MODULE<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token comment" spellcheck="true">
|
|
// This would name the module AwesomeCalendarManager instead
|
|
</span><span class="token comment" spellcheck="true">// RCT_EXPORT_MODULE(AwesomeCalendarManager);
|
|
</span>
|
|
@end</div><p>React Native will not expose any methods of <code>CalendarManager</code> to JavaScript unless explicitly told to. This is done using the <code>RCT_EXPORT_METHOD()</code> macro:</p><div class="prism language-javascript">#import <span class="token string">"CalendarManager.h"</span>
|
|
#import <React<span class="token operator">/</span>RCTLog<span class="token punctuation">.</span>h<span class="token operator">></span>
|
|
|
|
@implementation CalendarManager
|
|
|
|
<span class="token function">RCT_EXPORT_MODULE<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
|
|
<span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>name location<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>location<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
<span class="token function">RCTLogInfo<span class="token punctuation">(</span></span>@<span class="token string">"Pretending to create an event %@ at %@"</span><span class="token punctuation">,</span> name<span class="token punctuation">,</span> location<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p>Now, from your JavaScript file you can call the method like this:</p><div class="prism language-javascript">import <span class="token punctuation">{</span> NativeModules <span class="token punctuation">}</span> from <span class="token string">'react-native'</span><span class="token punctuation">;</span>
|
|
<span class="token keyword">var</span> CalendarManager <span class="token operator">=</span> NativeModules<span class="token punctuation">.</span>CalendarManager<span class="token punctuation">;</span>
|
|
CalendarManager<span class="token punctuation">.</span><span class="token function">addEvent<span class="token punctuation">(</span></span><span class="token string">'Birthday Party'</span><span class="token punctuation">,</span> <span class="token string">'4 Privet Drive, Surrey'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></div><blockquote><p><strong>NOTE</strong>: JavaScript method names</p><p>The name of the method exported to JavaScript is the native method's name up to the first colon. React Native also defines a macro called <code>RCT_REMAP_METHOD()</code> to specify the JavaScript method's name. This is useful when multiple native methods are the same up to the first colon and would have conflicting JavaScript names.</p></blockquote><p>The CalendarManager module is instantiated on the Objective-C side using a [CalendarManager new] call. The return type of bridge methods is always <code>void</code>. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).</p><h2><a class="anchor" name="argument-types"></a>Argument Types <a class="hash-link" href="docs/native-modules-ios.html#argument-types">#</a></h2><p><code>RCT_EXPORT_METHOD</code> supports all standard JSON object types, such as:</p><ul><li>string (<code>NSString</code>)</li><li>number (<code>NSInteger</code>, <code>float</code>, <code>double</code>, <code>CGFloat</code>, <code>NSNumber</code>)</li><li>boolean (<code>BOOL</code>, <code>NSNumber</code>)</li><li>array (<code>NSArray</code>) of any types from this list</li><li>object (<code>NSDictionary</code>) with string keys and values of any type from this list</li><li>function (<code>RCTResponseSenderBlock</code>)</li></ul><p>But it also works with any type that is supported by the <code>RCTConvert</code> class (see <a href="https://github.com/facebook/react-native/blob/master/React/Base/RCTConvert.h" target="_blank"><code>RCTConvert</code></a> for details). The <code>RCTConvert</code> helper functions all accept a JSON value as input and map it to a native Objective-C type or class.</p><p>In our <code>CalendarManager</code> example, we need to pass the event date to the native method. We can't send JavaScript Date objects over the bridge, so we need to convert the date to a string or number. We could write our native function like this:</p><div class="prism language-javascript"><span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>name location<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>location date<span class="token punctuation">:</span><span class="token punctuation">(</span>nonnull NSNumber <span class="token operator">*</span><span class="token punctuation">)</span>secondsSinceUnixEpoch<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
NSDate <span class="token operator">*</span>date <span class="token operator">=</span> <span class="token punctuation">[</span>RCTConvert NSDate<span class="token punctuation">:</span>secondsSinceUnixEpoch<span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p>or like this:</p><div class="prism language-javascript"><span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>name location<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>location date<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>ISO8601DateString<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
NSDate <span class="token operator">*</span>date <span class="token operator">=</span> <span class="token punctuation">[</span>RCTConvert NSDate<span class="token punctuation">:</span>ISO8601DateString<span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p>But by using the automatic type conversion feature, we can skip the manual conversion step completely, and just write:</p><div class="prism language-javascript"><span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>name location<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>location date<span class="token punctuation">:</span><span class="token punctuation">(</span>NSDate <span class="token operator">*</span><span class="token punctuation">)</span>date<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
<span class="token comment" spellcheck="true"> // Date is ready to use!
|
|
</span><span class="token punctuation">}</span></div><p>You would then call this from JavaScript by using either:</p><div class="prism language-javascript">CalendarManager<span class="token punctuation">.</span><span class="token function">addEvent<span class="token punctuation">(</span></span><span class="token string">'Birthday Party'</span><span class="token punctuation">,</span> <span class="token string">'4 Privet Drive, Surrey'</span><span class="token punctuation">,</span> date<span class="token punctuation">.</span><span class="token function">getTime<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true"> // passing date as number of milliseconds since Unix epoch</span></div><p>or</p><div class="prism language-javascript">CalendarManager<span class="token punctuation">.</span><span class="token function">addEvent<span class="token punctuation">(</span></span><span class="token string">'Birthday Party'</span><span class="token punctuation">,</span> <span class="token string">'4 Privet Drive, Surrey'</span><span class="token punctuation">,</span> date<span class="token punctuation">.</span><span class="token function">toISOString<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true"> // passing date as ISO-8601 string</span></div><p>And both values would get converted correctly to the native <code>NSDate</code>. A bad value, like an <code>Array</code>, would generate a helpful "RedBox" error message.</p><p>As <code>CalendarManager.addEvent</code> method gets more and more complex, the number of arguments will grow. Some of them might be optional. In this case it's worth considering changing the API a little bit to accept a dictionary of event attributes, like this:</p><div class="prism language-javascript">#import <React<span class="token operator">/</span>RCTConvert<span class="token punctuation">.</span>h<span class="token operator">></span>
|
|
|
|
<span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>name details<span class="token punctuation">:</span><span class="token punctuation">(</span>NSDictionary <span class="token operator">*</span><span class="token punctuation">)</span>details<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
NSString <span class="token operator">*</span>location <span class="token operator">=</span> <span class="token punctuation">[</span>RCTConvert NSString<span class="token punctuation">:</span>details<span class="token punctuation">[</span>@<span class="token string">"location"</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
NSDate <span class="token operator">*</span>time <span class="token operator">=</span> <span class="token punctuation">[</span>RCTConvert NSDate<span class="token punctuation">:</span>details<span class="token punctuation">[</span>@<span class="token string">"time"</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
|
|
<span class="token punctuation">}</span></div><p>and call it from JavaScript:</p><div class="prism language-javascript">CalendarManager<span class="token punctuation">.</span><span class="token function">addEvent<span class="token punctuation">(</span></span><span class="token string">'Birthday Party'</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
|
|
location<span class="token punctuation">:</span> <span class="token string">'4 Privet Drive, Surrey'</span><span class="token punctuation">,</span>
|
|
time<span class="token punctuation">:</span> date<span class="token punctuation">.</span><span class="token function">getTime<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">,</span>
|
|
description<span class="token punctuation">:</span> <span class="token string">'...'</span>
|
|
<span class="token punctuation">}</span><span class="token punctuation">)</span></div><blockquote><p><strong>NOTE</strong>: About array and map</p><p>Objective-C doesn't provide any guarantees about the types of values in these structures. Your native module might expect an array of strings, but if JavaScript calls your method with an array containing numbers and strings, you'll get an <code>NSArray</code> containing a mix of <code>NSNumber</code> and <code>NSString</code>. For arrays, <code>RCTConvert</code> provides some typed collections you can use in your method declaration, such as <code>NSStringArray</code>, or <code>UIColorArray</code>. For maps, it is the developer's responsibility to check the value types individually by manually calling <code>RCTConvert</code> helper methods.</p></blockquote><h2><a class="anchor" name="callbacks"></a>Callbacks <a class="hash-link" href="docs/native-modules-ios.html#callbacks">#</a></h2><blockquote><p><strong>WARNING</strong></p><p>This section is more experimental than others because we don't have a solid set of best practices around callbacks yet.</p></blockquote><p>Native modules also supports a special kind of argument- a callback. In most cases it is used to provide the function call result to JavaScript.</p><div class="prism language-javascript"><span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>findEvents<span class="token punctuation">:</span><span class="token punctuation">(</span>RCTResponseSenderBlock<span class="token punctuation">)</span>callback<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
NSArray <span class="token operator">*</span>events <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
|
|
<span class="token function">callback<span class="token punctuation">(</span></span>@<span class="token punctuation">[</span><span class="token punctuation">[</span>NSNull <span class="token keyword">null</span><span class="token punctuation">]</span><span class="token punctuation">,</span> events<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p><code>RCTResponseSenderBlock</code> accepts only one argument - an array of parameters to pass to the JavaScript callback. In this case we use Node's convention to make the first parameter an error object (usually <code>null</code> when there is no error) and the rest are the results of the function.</p><div class="prism language-javascript">CalendarManager<span class="token punctuation">.</span><span class="token function">findEvents<span class="token punctuation">(</span></span><span class="token punctuation">(</span>error<span class="token punctuation">,</span> events<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">{</span>
|
|
<span class="token keyword">if</span> <span class="token punctuation">(</span>error<span class="token punctuation">)</span> <span class="token punctuation">{</span>
|
|
console<span class="token punctuation">.</span><span class="token function">error<span class="token punctuation">(</span></span>error<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
|
|
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState<span class="token punctuation">(</span></span><span class="token punctuation">{</span>events<span class="token punctuation">:</span> events<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
<span class="token punctuation">}</span><span class="token punctuation">)</span></div><p>A native module should invoke its callback exactly once. It's okay to store the callback and invoke it later. This pattern is often used to wrap iOS APIs that require delegates - see <a href="https://github.com/facebook/react-native/blob/master/React/Modules/RCTAlertManager.m" target="_blank"><code>RCTAlertManager</code></a> for an example. If the callback is never invoked, some memory is leaked. If both <code>onSuccess</code> and <code>onFail</code> callbacks are passed, you should only invoke one of them.</p><p>If you want to pass error-like objects to JavaScript, use <code>RCTMakeError</code> from <a href="https://github.com/facebook/react-native/blob/master/React/Base/RCTUtils.h" target="_blank"><code>RCTUtils.h</code></a>. Right now this just passes an Error-shaped dictionary to JavaScript, but we would like to automatically generate real JavaScript <code>Error</code> objects in the future.</p><h2><a class="anchor" name="promises"></a>Promises <a class="hash-link" href="docs/native-modules-ios.html#promises">#</a></h2><p>Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's <code>async/await</code> syntax. When the last parameters of a bridged native method are an <code>RCTPromiseResolveBlock</code> and <code>RCTPromiseRejectBlock</code>, its corresponding JS method will return a JS Promise object.</p><p>Refactoring the above code to use a promise instead of callbacks looks like this:</p><div class="prism language-javascript"><span class="token function">RCT_REMAP_METHOD<span class="token punctuation">(</span></span>findEvents<span class="token punctuation">,</span>
|
|
findEventsWithResolver<span class="token punctuation">:</span><span class="token punctuation">(</span>RCTPromiseResolveBlock<span class="token punctuation">)</span>resolve
|
|
rejecter<span class="token punctuation">:</span><span class="token punctuation">(</span>RCTPromiseRejectBlock<span class="token punctuation">)</span>reject<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
NSArray <span class="token operator">*</span>events <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
|
|
<span class="token keyword">if</span> <span class="token punctuation">(</span>events<span class="token punctuation">)</span> <span class="token punctuation">{</span>
|
|
<span class="token function">resolve<span class="token punctuation">(</span></span>events<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
|
|
NSError <span class="token operator">*</span>error <span class="token operator">=</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
|
|
<span class="token function">reject<span class="token punctuation">(</span></span>@<span class="token string">"no_events"</span><span class="token punctuation">,</span> @<span class="token string">"There were no events"</span><span class="token punctuation">,</span> error<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
<span class="token punctuation">}</span></div><p>The JavaScript counterpart of this method returns a Promise. This means you can use the <code>await</code> keyword within an async function to call it and wait for its result:</p><div class="prism language-javascript">async <span class="token keyword">function</span> <span class="token function">updateEvents<span class="token punctuation">(</span></span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
|
|
<span class="token keyword">try</span> <span class="token punctuation">{</span>
|
|
<span class="token keyword">var</span> events <span class="token operator">=</span> await CalendarManager<span class="token punctuation">.</span><span class="token function">findEvents<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
|
|
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState<span class="token punctuation">(</span></span><span class="token punctuation">{</span> events <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">e</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
|
|
console<span class="token punctuation">.</span><span class="token function">error<span class="token punctuation">(</span></span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
<span class="token punctuation">}</span>
|
|
|
|
<span class="token function">updateEvents<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span></div><h2><a class="anchor" name="threading"></a>Threading <a class="hash-link" href="docs/native-modules-ios.html#threading">#</a></h2><p>The native module should not have any assumptions about what thread it is being called on. React Native invokes native modules methods on a separate serial GCD queue, but this is an implementation detail and might change. The <code>- (dispatch_queue_t)methodQueue</code> method allows the native module to specify which queue its methods should be run on. For example, if it needs to use a main-thread-only iOS API, it should specify this via:</p><div class="prism language-javascript"><span class="token operator">-</span> <span class="token punctuation">(</span>dispatch_queue_t<span class="token punctuation">)</span>methodQueue
|
|
<span class="token punctuation">{</span>
|
|
<span class="token keyword">return</span> <span class="token function">dispatch_get_main_queue<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p>Similarly, if an operation may take a long time to complete, the native module should not block and can specify it's own queue to run operations on. For example, the <code>RCTAsyncLocalStorage</code> module creates it's own queue so the React queue isn't blocked waiting on potentially slow disk access:</p><div class="prism language-javascript"><span class="token operator">-</span> <span class="token punctuation">(</span>dispatch_queue_t<span class="token punctuation">)</span>methodQueue
|
|
<span class="token punctuation">{</span>
|
|
<span class="token keyword">return</span> <span class="token function">dispatch_queue_create<span class="token punctuation">(</span></span><span class="token string">"com.facebook.React.AsyncLocalStorageQueue"</span><span class="token punctuation">,</span> DISPATCH_QUEUE_SERIAL<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p>The specified <code>methodQueue</code> will be shared by all of the methods in your module. If <em>just one</em> of your methods is long-running (or needs to be run on a different queue than the others for some reason), you can use <code>dispatch_async</code> inside the method to perform that particular method's code on another queue, without affecting the others:</p><div class="prism language-javascript"><span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>doSomethingExpensive<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>param callback<span class="token punctuation">:</span><span class="token punctuation">(</span>RCTResponseSenderBlock<span class="token punctuation">)</span>callback<span class="token punctuation">)</span>
|
|
<span class="token punctuation">{</span>
|
|
<span class="token function">dispatch_async<span class="token punctuation">(</span></span><span class="token function">dispatch_get_global_queue<span class="token punctuation">(</span></span>DISPATCH_QUEUE_PRIORITY_DEFAULT<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">^</span><span class="token punctuation">{</span>
|
|
<span class="token comment" spellcheck="true"> // Call long-running code on background thread
|
|
</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
|
|
<span class="token comment" spellcheck="true"> // You can invoke callback from any thread/queue
|
|
</span> <span class="token function">callback<span class="token punctuation">(</span></span>@<span class="token punctuation">[</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><blockquote><p><strong>NOTE</strong>: Sharing dispatch queues between modules</p><p>The <code>methodQueue</code> method will be called once when the module is initialized, and then retained by the bridge, so there is no need to retain the queue yourself, unless you wish to make use of it within your module. However, if you wish to share the same queue between multiple modules then you will need to ensure that you retain and return the same queue instance for each of them; merely returning a queue of the same name for each won't work.</p></blockquote><h2><a class="anchor" name="dependency-injection"></a>Dependency Injection <a class="hash-link" href="docs/native-modules-ios.html#dependency-injection">#</a></h2><p>The bridge initializes any registered RCTBridgeModules automatically, however you may wish to instantiate your own module instances (so you may inject dependencies, for example).</p><p>You can do this by creating a class that implements the RCTBridgeDelegate Protocol, initializing an RCTBridge with the delegate as an argument and initialising a RCTRootView with the initialized bridge.</p><div class="prism language-javascript">id<RCTBridgeDelegate<span class="token operator">></span> moduleInitialiser <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span>classThatImplementsRCTBridgeDelegate alloc<span class="token punctuation">]</span> init<span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
|
|
RCTBridge <span class="token operator">*</span>bridge <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span>RCTBridge alloc<span class="token punctuation">]</span> initWithDelegate<span class="token punctuation">:</span>moduleInitialiser launchOptions<span class="token punctuation">:</span>nil<span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
|
|
RCTRootView <span class="token operator">*</span>rootView <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span>RCTRootView alloc<span class="token punctuation">]</span>
|
|
initWithBridge<span class="token punctuation">:</span>bridge
|
|
moduleName<span class="token punctuation">:</span>kModuleName
|
|
initialProperties<span class="token punctuation">:</span>nil<span class="token punctuation">]</span><span class="token punctuation">;</span></div><h2><a class="anchor" name="exporting-constants"></a>Exporting Constants <a class="hash-link" href="docs/native-modules-ios.html#exporting-constants">#</a></h2><p>A native module can export constants that are immediately available to JavaScript at runtime. This is useful for communicating static data that would otherwise require a round-trip through the bridge.</p><div class="prism language-javascript"><span class="token operator">-</span> <span class="token punctuation">(</span>NSDictionary <span class="token operator">*</span><span class="token punctuation">)</span>constantsToExport
|
|
<span class="token punctuation">{</span>
|
|
<span class="token keyword">return</span> @<span class="token punctuation">{</span> @<span class="token string">"firstDayOfTheWeek"</span><span class="token punctuation">:</span> @<span class="token string">"Monday"</span> <span class="token punctuation">}</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span></div><p>JavaScript can use this value right away, synchronously:</p><div class="prism language-javascript">console<span class="token punctuation">.</span><span class="token function">log<span class="token punctuation">(</span></span>CalendarManager<span class="token punctuation">.</span>firstDayOfTheWeek<span class="token punctuation">)</span><span class="token punctuation">;</span></div><p>Note that the constants are exported only at initialization time, so if you change <code>constantsToExport</code> values at runtime it won't affect the JavaScript environment.</p><h3><a class="anchor" name="enum-constants"></a>Enum Constants <a class="hash-link" href="docs/native-modules-ios.html#enum-constants">#</a></h3><p>Enums that are defined via <code>NS_ENUM</code> cannot be used as method arguments without first extending RCTConvert.</p><p>In order to export the following <code>NS_ENUM</code> definition:</p><div class="prism language-javascript">typedef <span class="token function">NS_ENUM<span class="token punctuation">(</span></span>NSInteger<span class="token punctuation">,</span> UIStatusBarAnimation<span class="token punctuation">)</span> <span class="token punctuation">{</span>
|
|
UIStatusBarAnimationNone<span class="token punctuation">,</span>
|
|
UIStatusBarAnimationFade<span class="token punctuation">,</span>
|
|
UIStatusBarAnimationSlide<span class="token punctuation">,</span>
|
|
<span class="token punctuation">}</span><span class="token punctuation">;</span></div><p>You must create a class extension of RCTConvert like so:</p><div class="prism language-javascript">@implementation RCTConvert <span class="token punctuation">(</span>StatusBarAnimation<span class="token punctuation">)</span>
|
|
<span class="token function">RCT_ENUM_CONVERTER<span class="token punctuation">(</span></span>UIStatusBarAnimation<span class="token punctuation">,</span> <span class="token punctuation">(</span>@<span class="token punctuation">{</span> @<span class="token string">"statusBarAnimationNone"</span> <span class="token punctuation">:</span> @<span class="token punctuation">(</span>UIStatusBarAnimationNone<span class="token punctuation">)</span><span class="token punctuation">,</span>
|
|
@<span class="token string">"statusBarAnimationFade"</span> <span class="token punctuation">:</span> @<span class="token punctuation">(</span>UIStatusBarAnimationFade<span class="token punctuation">)</span><span class="token punctuation">,</span>
|
|
@<span class="token string">"statusBarAnimationSlide"</span> <span class="token punctuation">:</span> @<span class="token punctuation">(</span>UIStatusBarAnimationSlide<span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
|
|
UIStatusBarAnimationNone<span class="token punctuation">,</span> integerValue<span class="token punctuation">)</span>
|
|
@end</div><p>You can then define methods and export your enum constants like this:</p><div class="prism language-javascript"><span class="token operator">-</span> <span class="token punctuation">(</span>NSDictionary <span class="token operator">*</span><span class="token punctuation">)</span>constantsToExport
|
|
<span class="token punctuation">{</span>
|
|
<span class="token keyword">return</span> @<span class="token punctuation">{</span> @<span class="token string">"statusBarAnimationNone"</span> <span class="token punctuation">:</span> @<span class="token punctuation">(</span>UIStatusBarAnimationNone<span class="token punctuation">)</span><span class="token punctuation">,</span>
|
|
@<span class="token string">"statusBarAnimationFade"</span> <span class="token punctuation">:</span> @<span class="token punctuation">(</span>UIStatusBarAnimationFade<span class="token punctuation">)</span><span class="token punctuation">,</span>
|
|
@<span class="token string">"statusBarAnimationSlide"</span> <span class="token punctuation">:</span> @<span class="token punctuation">(</span>UIStatusBarAnimationSlide<span class="token punctuation">)</span> <span class="token punctuation">}</span>
|
|
<span class="token punctuation">}</span><span class="token punctuation">;</span>
|
|
|
|
<span class="token function">RCT_EXPORT_METHOD<span class="token punctuation">(</span></span>updateStatusBarAnimation<span class="token punctuation">:</span><span class="token punctuation">(</span>UIStatusBarAnimation<span class="token punctuation">)</span>animation
|
|
completion<span class="token punctuation">:</span><span class="token punctuation">(</span>RCTResponseSenderBlock<span class="token punctuation">)</span>callback<span class="token punctuation">)</span></div><p>Your enum will then be automatically unwrapped using the selector provided (<code>integerValue</code> in the above example) before being passed to your exported method.</p><h2><a class="anchor" name="sending-events-to-javascript"></a>Sending Events to JavaScript <a class="hash-link" href="docs/native-modules-ios.html#sending-events-to-javascript">#</a></h2><p>The native module can signal events to JavaScript without being invoked directly. The preferred way to do this is to subclass <code>RCTEventEmitter</code>, implement <code>suppportEvents</code> and call <code>self sendEventWithName</code>:</p><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManager.h
|
|
</span>#import <React<span class="token operator">/</span>RCTBridgeModule<span class="token punctuation">.</span>h<span class="token operator">></span>
|
|
#import <React<span class="token operator">/</span>RCTEventEmitter<span class="token punctuation">.</span>h<span class="token operator">></span>
|
|
|
|
@interface <span class="token class-name">CalendarManager</span> <span class="token punctuation">:</span> RCTEventEmitter <RCTBridgeModule<span class="token operator">></span>
|
|
|
|
@end</div><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManager.m
|
|
</span>#import <span class="token string">"CalendarManager.h"</span>
|
|
|
|
@implementation CalendarManager
|
|
|
|
<span class="token function">RCT_EXPORT_MODULE<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
|
|
<span class="token operator">-</span> <span class="token punctuation">(</span>NSArray<NSString <span class="token operator">*</span><span class="token operator">></span> <span class="token operator">*</span><span class="token punctuation">)</span>supportedEvents
|
|
<span class="token punctuation">{</span>
|
|
<span class="token keyword">return</span> @<span class="token punctuation">[</span>@<span class="token string">"EventReminder"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
|
|
<span class="token operator">-</span> <span class="token punctuation">(</span>void<span class="token punctuation">)</span>calendarEventReminderReceived<span class="token punctuation">:</span><span class="token punctuation">(</span>NSNotification <span class="token operator">*</span><span class="token punctuation">)</span>notification
|
|
<span class="token punctuation">{</span>
|
|
NSString <span class="token operator">*</span>eventName <span class="token operator">=</span> notification<span class="token punctuation">.</span>userInfo<span class="token punctuation">[</span>@<span class="token string">"name"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">[</span>self sendEventWithName<span class="token punctuation">:</span>@<span class="token string">"EventReminder"</span> body<span class="token punctuation">:</span>@<span class="token punctuation">{</span>@<span class="token string">"name"</span><span class="token punctuation">:</span> eventName<span class="token punctuation">}</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
|
|
@end</div><p>JavaScript code can subscribe to these events by creating a new <code>NativeEventEmitter</code> instance around your module.</p><div class="prism language-javascript">import <span class="token punctuation">{</span> NativeEventEmitter<span class="token punctuation">,</span> NativeModules <span class="token punctuation">}</span> from <span class="token string">'react-native'</span><span class="token punctuation">;</span>
|
|
const <span class="token punctuation">{</span> CalendarManager <span class="token punctuation">}</span> <span class="token operator">=</span> NativeModules<span class="token punctuation">;</span>
|
|
|
|
const calendarManagerEmitter <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NativeEventEmitter</span><span class="token punctuation">(</span>CalendarManager<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
|
|
const subscription <span class="token operator">=</span> calendarManagerEmitter<span class="token punctuation">.</span><span class="token function">addListener<span class="token punctuation">(</span></span>
|
|
<span class="token string">'EventReminder'</span><span class="token punctuation">,</span>
|
|
<span class="token punctuation">(</span>reminder<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> console<span class="token punctuation">.</span><span class="token function">log<span class="token punctuation">(</span></span>reminder<span class="token punctuation">.</span>name<span class="token punctuation">)</span>
|
|
<span class="token punctuation">)</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token comment" spellcheck="true">
|
|
// Don't forget to unsubscribe, typically in componentWillUnmount
|
|
</span>subscription<span class="token punctuation">.</span><span class="token function">remove<span class="token punctuation">(</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span></div><p>For more examples of sending events to JavaScript, see <a href="https://github.com/facebook/react-native/blob/master/Libraries/Geolocation/RCTLocationObserver.m" target="_blank"><code>RCTLocationObserver</code></a>.</p><h3><a class="anchor" name="optimizing-for-zero-listeners"></a>Optimizing for zero listeners <a class="hash-link" href="docs/native-modules-ios.html#optimizing-for-zero-listeners">#</a></h3><p>You will receive a warning if you expend resources unnecessarily by emitting an event while there are no listeners. To avoid this, and to optimize your module's workload (e.g. by unsubscribing from upstream notifications or pausing background tasks), you can override <code>startObserving</code> and <code>stopObserving</code> in your <code>RCTEventEmitter</code> subclass.</p><div class="prism language-javascript">@implementation CalendarManager
|
|
<span class="token punctuation">{</span>
|
|
bool hasListeners<span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
<span class="token comment" spellcheck="true">
|
|
// Will be called when this module's first listener is added.
|
|
</span><span class="token operator">-</span><span class="token punctuation">(</span>void<span class="token punctuation">)</span>startObserving <span class="token punctuation">{</span>
|
|
hasListeners <span class="token operator">=</span> YES<span class="token punctuation">;</span>
|
|
<span class="token comment" spellcheck="true"> // Set up any upstream listeners or background tasks as necessary
|
|
</span><span class="token punctuation">}</span>
|
|
<span class="token comment" spellcheck="true">
|
|
// Will be called when this module's last listener is removed, or on dealloc.
|
|
</span><span class="token operator">-</span><span class="token punctuation">(</span>void<span class="token punctuation">)</span>stopObserving <span class="token punctuation">{</span>
|
|
hasListeners <span class="token operator">=</span> NO<span class="token punctuation">;</span>
|
|
<span class="token comment" spellcheck="true"> // Remove upstream listeners, stop unnecessary background tasks
|
|
</span><span class="token punctuation">}</span>
|
|
|
|
<span class="token operator">-</span> <span class="token punctuation">(</span>void<span class="token punctuation">)</span>calendarEventReminderReceived<span class="token punctuation">:</span><span class="token punctuation">(</span>NSNotification <span class="token operator">*</span><span class="token punctuation">)</span>notification
|
|
<span class="token punctuation">{</span>
|
|
NSString <span class="token operator">*</span>eventName <span class="token operator">=</span> notification<span class="token punctuation">.</span>userInfo<span class="token punctuation">[</span>@<span class="token string">"name"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token keyword">if</span> <span class="token punctuation">(</span>hasListeners<span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment" spellcheck="true"> // Only send events if anyone is listening
|
|
</span> <span class="token punctuation">[</span>self sendEventWithName<span class="token punctuation">:</span>@<span class="token string">"EventReminder"</span> body<span class="token punctuation">:</span>@<span class="token punctuation">{</span>@<span class="token string">"name"</span><span class="token punctuation">:</span> eventName<span class="token punctuation">}</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
|
|
<span class="token punctuation">}</span>
|
|
<span class="token punctuation">}</span></div><h2><a class="anchor" name="exporting-swift"></a>Exporting Swift <a class="hash-link" href="docs/native-modules-ios.html#exporting-swift">#</a></h2><p>Swift doesn't have support for macros so exposing it to React Native requires a bit more setup but works relatively the same.</p><p>Let's say we have the same <code>CalendarManager</code> but as a Swift class:</p><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManager.swift
|
|
</span>
|
|
@<span class="token function">objc<span class="token punctuation">(</span></span>CalendarManager<span class="token punctuation">)</span>
|
|
class <span class="token class-name">CalendarManager</span><span class="token punctuation">:</span> NSObject <span class="token punctuation">{</span>
|
|
|
|
@<span class="token function">objc<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span>location<span class="token punctuation">:</span>date<span class="token punctuation">:</span><span class="token punctuation">)</span>
|
|
func <span class="token function">addEvent<span class="token punctuation">(</span></span>name<span class="token punctuation">:</span> String<span class="token punctuation">,</span> location<span class="token punctuation">:</span> String<span class="token punctuation">,</span> date<span class="token punctuation">:</span> NSNumber<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> Void <span class="token punctuation">{</span>
|
|
<span class="token comment" spellcheck="true"> // Date is ready to use!
|
|
</span> <span class="token punctuation">}</span>
|
|
|
|
<span class="token punctuation">}</span></div><blockquote><p><strong>NOTE</strong>: It is important to use the @objc modifiers to ensure the class and functions are exported properly to the Objective-C runtime.</p></blockquote><p>Then create a private implementation file that will register the required information with the React Native bridge:</p><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManagerBridge.m
|
|
</span>#import <React<span class="token operator">/</span>RCTBridgeModule<span class="token punctuation">.</span>h<span class="token operator">></span>
|
|
|
|
@interface <span class="token class-name">RCT_EXTERN_MODULE</span><span class="token punctuation">(</span>CalendarManager<span class="token punctuation">,</span> NSObject<span class="token punctuation">)</span>
|
|
|
|
<span class="token function">RCT_EXTERN_METHOD<span class="token punctuation">(</span></span>addEvent<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>name location<span class="token punctuation">:</span><span class="token punctuation">(</span>NSString <span class="token operator">*</span><span class="token punctuation">)</span>location date<span class="token punctuation">:</span><span class="token punctuation">(</span>nonnull NSNumber <span class="token operator">*</span><span class="token punctuation">)</span>date<span class="token punctuation">)</span>
|
|
|
|
@end</div><p>For those of you new to Swift and Objective-C, whenever you <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html" target="_blank">mix the two languages in an iOS project</a>, you will also need an additional bridging file, known as a bridging header, to expose the Objective-C files to Swift. Xcode will offer to create this header file for you if you add your Swift file to your app through the Xcode <code>File>New File</code> menu option. You will need to import <code>RCTBridgeModule.h</code> in this header file.</p><div class="prism language-javascript"><span class="token comment" spellcheck="true">// CalendarManager-Bridging-Header.h
|
|
</span>#import <React<span class="token operator">/</span>RCTBridgeModule<span class="token punctuation">.</span>h<span class="token operator">></span></div><p>You can also use <code>RCT_EXTERN_REMAP_MODULE</code> and <code>RCT_EXTERN_REMAP_METHOD</code> to alter the JavaScript name of the module or methods you are exporting. For more information see <a href="https://github.com/facebook/react-native/blob/master/React/Base/RCTBridgeModule.h" target="_blank"><code>RCTBridgeModule</code></a>.</p></div><div class="docs-prevnext"><a class="docs-prev" href="docs/upgrading.html#content">← Prev</a><a class="docs-next" href="docs/native-components-ios.html#content">Next →</a></div><p class="edit-page-block">You can <a target="_blank" href="https://github.com/facebook/react-native/blob/master/docs/NativeModulesIOS.md">edit the content above on GitHub</a> and send us a pull request!</p></div></section><footer class="nav-footer"><section class="sitemap"><a href="/react-native" class="nav-home"><img src="img/header_logo.png" alt="React Native" width="66" height="58"></a><div><h5><a href="docs/">Docs</a></h5><a href="docs/getting-started.html">Getting Started</a><a href="docs/tutorial.html">Tutorial</a><a href="docs/integration-with-existing-apps.html">Integration With Existing Apps</a><a href="docs/more-resources.html">More Resources</a></div><div><h5><a href="/react-native/support.html">Community</a></h5><a href="/react-native/showcase.html">Showcase</a><a href="http://www.meetup.com/topics/react-native/" target="_blank">Upcoming Events</a><a href="https://www.facebook.com/groups/react.native.community" target="_blank">Facebook Group</a><a href="https://twitter.com/reactnative" target="_blank">Twitter</a></div><div><h5><a href="/react-native/support.html">Help</a></h5><a href="http://stackoverflow.com/questions/tagged/react-native" target="_blank">Stack Overflow</a><a href="https://discord.gg/0ZcbPKXt5bZjGY5n">Reactiflux Chat</a><a href="/react-native/versions.html" target="_blank">Latest Releases</a><a href="https://react-native.canny.io/feature-requests" target="_blank">Feature Requests</a></div><div><h5>More</h5><a href="/react-native/blog">Blog</a><a href="https://github.com/facebook/react-native" target="_blank">GitHub</a><a href="http://facebook.github.io/react/" target="_blank">React</a></div></section><section class="newsletter"><div id="mc_embed_signup"><form action="//reactnative.us10.list-manage.com/subscribe/post?u=db0dd948e2b729ee62625b1a8&id=47cd41008f" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate><div id="mc_embed_signup_scroll"><label for="mce-EMAIL"><h5>Get the React Native Newsletter</h5></label><input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required><div style="position:absolute;left:-5000px;" aria-hidden="true"><input type="text" name="b_db0dd948e2b729ee62625b1a8_47cd41008f" tabindex="-1" value=""></div><div class="clear"><input type="submit" value="Sign up" name="subscribe" id="mc-embedded-subscribe" class="button"></div></div></form></div></section><a href="https://code.facebook.com/projects/" target="_blank" class="fbOpenSource"><img src="img/oss_logo.png" alt="Facebook Open Source" width="170" height="45"></a><section class="copyright">Copyright © 2017 Facebook Inc.</section></footer></div><div id="fb-root"></div><script type="text/javascript" src="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.js"></script><script>
|
|
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
|
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
|
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
|
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
|
|
ga('create', 'UA-41298772-2', 'facebook.github.io');
|
|
ga('send', 'pageview');
|
|
|
|
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)
|
|
){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";
|
|
fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
|
|
|
|
docsearch({
|
|
apiKey: '2c98749b4a1e588efec53b2acec13025',
|
|
indexName: 'react-native-versions',
|
|
inputSelector: '#algolia-doc-search',
|
|
algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 }
|
|
});
|
|
</script><script src="js/scripts.js"></script><script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js"></script><script type="text/javascript">(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script><script type="text/javascript" src="https://snack.expo.io/embed.js"></script></body></html> |