While React Native is a relatively new framework, native iOS application development has been around since March 2008. Through the years, the development community has released many open source components, companies have developed countless internal artifacts and, more importantly, Apple has provided us with a library of first party components that we can embed in our application. Weโre going to take a look at how we can take an existing native iOS UI View Controller and render it inside our React Native app.
Letโs Visualize the App
For us to figure out how to render an external iOS View Controller we should visualize what our Native App will look like. On the left hand side, we have our view controller that will render and be able to communicate with our React Native code on the right.
In order to accomplish the rendering of the view and facilitate communication to the React Native app, we need to create a React Native Module that logically encapsulates this View Controller instance.
Before we continue further, we should take a look at the component structure of a standard React Native iOS application.
The one important component to note here is the instance of UIViewController (named rootViewController in your AppDelegate implementation).
Our next step here is to expose our rootViewController variable as a property attached to our AppDelegate. This will allow for other classes to reference this controller, and in our case if they are an instance of UIViewController present themselves on the screen.
Our Native Module
Now that we have our rootViewController accessible from outside our AppDelegate we can create our Native Module that will wrap the view we want to display. For our example we will be using the MPMediaPickerController. This is a subclass of UIViewController that is responsible for displaying the iOS Media Library (aka iPod library). The MPMediaPickerController is an excellent example since it is a modal controller and also implements a delegate (MPMediaPickerControllerDelegate) that we will leverage.
Here is the sample MediaController class we will be implementing. Note: to support playing the audio track selected, we are including use of the AVAudioPlayer class.
The following are a few snippets that handle the two major things we need:
1) Displaying and hiding the media library
2) Communicating with our React Native application in regards to what was done in the MPMediaPickerController
Here weโre firing an event SongPlaying through the RCTBridge with the track title.
Here we are adding a listener for the event and updating our state accordingly.
For further reference, here is the full implementation of our MediaController
Stan Bershadskiy
Related Posts
-
React Navigation and Redux in React Native Applications
In React Native, the question of โhow am I going to navigate from one screen…
-
Using ES2016 Decorators in React Native
*picture courtesy of pixabayDecorators are a popular bit of functionality currently in Stage 1 of…