Importing Modules into the Xcode Project

What if you want to use a community React Native component, i.e., something that is not part of react-native, but is provided as a standalone npm module? You can import a module into your project!

In Timer, we need to play the sound when time is up. There’s no official component for sounds as of this writing (Jan 2016), but there are several userland modules. One of them is react-native-audioplayer. First, install it with npm in the project folder:

1 $ npm install react-native-audioplayer@0.2.0 --save

We’re focusing on iOS at the moment, so the installation is as follows:

  1. Open your project in Xcode.
  2. In Xcode, find the Project Navigator in the left sidebar.
  3. In the Project Navigator, right-click Libraries.
  4. In the context menu, click Add Files to “timer”. (Substitute another project name for “timer” if needed.)
  5. Navigate to node_modules/react-native-audioplayer. Add the file RNAudioPlayer.xcodeproj. The result is shown in Figure 5.
Figure 5: Adding `RNAudioPlayer` to XCode project to play audio
Figure 5: Adding RNAudioPlayer to XCode project to play audio
  1. In the Project Navigator, select your project (timer).
  2. Click the build target for timer in the Targets list (figure 9-X).
Figure 6: Selecting a build target from Targets
Figure 6: Selecting a build target from Targets
  1. Click on the Build Phases tab to open it.
  2. Expand Link Binary With Libraries by clicking on it.
  3. Click on the plus button (+) and add libRNAudioPlayer.a under Workspace, or just drag and drop libRNAudioPlayer.a from the Project Navigator. It’s under Libraries/RNAudioPlayer.xcodeproj/Products.
  4. Run your project (press Command+R or click the black rectangle signifying “play”).

If you did everything correctly, in the index.ios.js file, you can import the module with require():

1 AudioPlayer = require('react-native-audioplayer')

And play the sound with play():

1 AudioPlayer.play('flute_c_long_01.wav')

The sound file needs to be included in the bundle. To do so, select Copy Bundle Resources and add flute_c_long_01.wav, or your own sound file as shown in Figure 7.

Figure 7: Adding a wav file to the bundle
Figure 7: Adding a wav file to the bundle

That’s all the prep. Now we can implement Timer!