DEV Community

Cover image for Integrating Native iOS Code with React Native Using Swift: A Comprehensive Guide
jai prakash sharma
jai prakash sharma

Posted on

Integrating Native iOS Code with React Native Using Swift: A Comprehensive Guide

Introduction

In the world of mobile application development, React Native has gained immense popularity due to its ability to build cross-platform apps with a single codebase. However, there may be situations where you need to access native iOS features that are not directly available in JavaScript. This is where integrating native iOS code using Swift comes into play. In this guide, we’ll explore the process of bridging React Native with native iOS code using Swift, allowing you to unlock the full potential of iOS functionalities in your React Native applications.

Why Integrate Native iOS Code in React Native?

While React Native provides a robust set of APIs for building mobile applications, there are several scenarios where you might need to tap into native iOS features:

  • Performance Optimization: For computationally intensive tasks or heavy graphics operations, native modules can offer better performance than JavaScript.
  • Accessing Device Features: Features like camera, GPS, and accelerometer may require native APIs for better functionality and performance.
  • Utilizing Third-Party SDKs: Sometimes, the functionality you need is only available through native SDKs, making bridging essential.

Setting Up Your React Native Project for Native Code

Before you can start writing Swift code, ensure that your React Native project is set up to accommodate native modules.

1. Install Xcode

Ensure you have the latest version of Xcode installed on your Mac. This is essential for developing iOS applications.

2. Create a New React Native Project

If you haven't already created a React Native project, you can do so with the following command:



npx react-native init MyReactNativeApp
cd MyReactNativeApp

Enter fullscreen mode Exit fullscreen mode



  1. Open the iOS Folder in Xcode

Navigate to the ios directory of your React Native project and open it in Xcode:



cd ios && open MyReactNativeApp.xcworkspace

Enter fullscreen mode Exit fullscreen mode



  1. Add a Swift File

In Xcode, right-click on the project navigator, select New File > Swift File, and name it NativeModule.swift.

5. Create a Bridging Header

When prompted to create a bridging header, accept it. This bridging header allows your React Native app (which is written in Objective-C) to communicate with the Swift code you are about to write.

Writing Your Native Module in Swift

Now that your project is set up, let’s create a simple native module that adds two numbers and returns the result to the JavaScript side.

Step 1: Implementing the Native Module

Open your NativeModule.swift file and add the following code:



import Foundation
import React

@objc(NativeModule)
class NativeModule: NSObject {

<span class="kd">@objc</span>
<span class="kd">func</span> <span class="nf">add</span><span class="p">(</span><span class="n">_</span> <span class="nv">a</span><span class="p">:</span> <span class="kt">NSNumber</span><span class="p">,</span> <span class="nv">b</span><span class="p">:</span> <span class="kt">NSNumber</span><span class="p">,</span> <span class="nv">callback</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="kt">RCTResponseSenderBlock</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">sum</span> <span class="o">=</span> <span class="n">a</span><span class="o">.</span><span class="n">doubleValue</span> <span class="o">+</span> <span class="n">b</span><span class="o">.</span><span class="n">doubleValue</span>
    <span class="nf">callback</span><span class="p">([</span><span class="kt">NSNull</span><span class="p">(),</span> <span class="n">sum</span><span class="p">])</span>  <span class="c1">// Sending the result back to JavaScript</span>
<span class="p">}</span>

<span class="kd">static</span> <span class="kd">func</span> <span class="nf">requiresMainQueueSetup</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Bool</span> <span class="p">{</span>
    <span class="k">return</span> <span class="kc">false</span>
<span class="p">}</span>
Enter fullscreen mode Exit fullscreen mode

}

Enter fullscreen mode Exit fullscreen mode




Explanation of the Code:

  • @objc(NativeModule): This exposes the Swift class to Objective-C, allowing React Native to interact with it.
  • add(_🅱️callback:): This method takes two numbers, computes their sum, and sends the result back through a callback.
  • requiresMainQueueSetup(): This method informs React Native whether the module needs to be initialized on the main thread. For this module, returning false is sufficient since there are no UI updates.

Step 2: Exposing the Native Module to React Native

To make the NativeModule accessible in React Native, you need to create an Objective-C interface.

  1. Create a new Objective-C file named NativeModule.m and add the following code:


#import <Foundation/Foundation.h>

import <React/RCTBridgeModule.h>


@interface RCT_EXTERN_MODULE(NativeModule, NSObject)
RCT_EXTERN_METHOD(add:(nonnull NSNumber )a b:(nonnull NSNumber )b callback:(RCTResponseSenderBlock)callback)
@end

Enter fullscreen mode Exit fullscreen mode




Explanation of the Code:

  • RCT_EXTERN_MODULE: This macro exposes the Swift class NativeModule to React Native.
  • RCT_EXTERN_METHOD: This exposes the add method to JavaScript, specifying its parameters and callback.

Using Your Native Module in React Native

Now that your native module is ready, you can call the add function from your React Native code. Here’s how to do it:

  1. Open your JavaScript file (e.g., App.js) and import the module:


import React from 'react';
import { View, Text, Button, NativeModules } from 'react-native';

const { NativeModule } = NativeModules;

const App = () => {
const handleAdd = () => {
NativeModule.add(5, 10, (error, sum) => {
if (error) {
console.error(error);
} else {
console.log('Sum is:', sum); // Output: Sum is: 15
}
});
};

return (
<View>
<Text>Integrating Native iOS Code with React Native</Text>
<Button title="Add Numbers" onPress={handleAdd} />
</View>
);
};

export default App;

Enter fullscreen mode Exit fullscreen mode




Explanation of the Code:

  • We import the NativeModule from NativeModules.
  • The handleAdd function calls the add method, passing two numbers (5 and 10) and a callback to handle the result.

Conclusion

Integrating native iOS code with React Native using Swift allows you to harness the full power of iOS features and significantly enhance your app's performance. In this guide, we demonstrated how to create a simple native module for adding numbers, expose it to React Native, and use it within your application.

By following the principles outlined in this guide, you can extend the functionality of your React Native applications, leveraging the unique capabilities of iOS while maintaining a common codebase. Start exploring native modules to elevate your React Native projects today!

Top comments (0)