Skip to main content

How to communicate between React Native and Swift using Bridging

In this article we will learn how can we achieve communication between React Native and Swift code. As we know React Native (RN) is great for building cross platform apps, but during development of react native app we might come across a situation where we need to call native code written in swift.

This is where bridge module comes in, which allows us to communicate with the native layer of the application. If we are developing app in React Native for iOS and Android platform then we need to create a bridge for each platform. In this article we will discuss creation of React Native Bridge for iOS only.

So Let’s start

To better understand the concept we will create sample DemoApp in react native using react native CLI. Below are the commands to setup new project in react native.

·      react-native init DemoApp
·      cd DemoApp
·      react-native run-ios

On running the app on iOS simulator, you will be presented with following screen.
react native first screen
React Native welcome screen


Moving to the coding part

In this App, we will store some sensitive data in keychain. I am using  SwiftKeychainWrapper  cocoapod library to store data securely in iOS keychain.

This pod can be installed by adding pod ‘SwiftKeychainWrapper’ line to your podfile. Make sure to run command pod install in terminal to install the required pod in your project.

Let’s now edit our App.js react native file with below code:


In the above code, we simply added one TextInput and Button on the screen. In this, we will save the password enter by user in the TextInput field on the button click.

handleChangePassword method is used to store the text entered in the TextInput field inside the password state.

If you run your code now then your iOS screen will look like below:


Next we need to open ios/DemoApp.xcworkspace in Xcode.
Create a swift file

·      CMD + N
·      Select Swift file
·      Name your file KeyChainWrapper
·      In the group dropdown, make sure to select group DemoApp not the project itself.

Configure the Objective-C Bridging Header

After we created swift file, we should be prompted to choose if we want to configure an Objective-C Bridging Header. Select Create Bridging Header option.
Objective C Bridging Header

Now open bridging header file just created above and add below header:

#import "React/RCTBridgeModule.h"


  RCTBridgeModule will provide an interface to register a bridge module.

Now open your keyChainWrapper swift file. It should be inherited from NSObject so that it can be exposed to Obj-C

Now Let’s expose our swift file to JS

To do this we need to use Obj-C Macro available in React Native. To use these Obj-C Macros, we need a new Obj-C file. So follow below steps to create new Obj-C file

·      CMD+N
·      Select Objective-C file
·      Name your file KeyChainWrapper

Now we will import RCTBridgeModule so that we can use Macro to bridge the native code
We will use RCT_EXTERN_MODULE Macro to expose our KeyChainWrapper class to JS

·      The first argument is the name of your swift class
·      The second is its superclass

Accessing your module from JS

Now it’s time to check swift class access from JS. So open your App.js react file and import NativeModules from react-native and let’s see if we can access our keyChainWrapper swift class from componentDidMount() method.


 Any module exposed to React Native should be available as a property on the NativeModules object. If we debug it remotely, we will get undefined because react native doesn’t expose native class if we don’t expose some of its methods. So let’s do that now.

Open your KeyChainWrapper swift class and add below method.
In above method, we are receiving password text entered by user from react native code and saving it securely in iOS Keychain. Here, please note that we need to pass an Array in the callback and have to used @objc directive for each property and method that needs to accessed from Obj-C.

Next we have to expose the method to React Native bridge, open your KeyChainWrapper Objective C .m class and declare savePassword method inside RCT_EXTERN_METHOD as below:



Now, it’s time to call this method from our React Native code. So open App.js and declare the handler for save password button as below:
In above code we are sending the password entered by user on button click to our swift class where it is getting saved securely in iOS keychain.

Main queue setup warning

We might get a warning which tells that we didn’t implemented the requiresMainQueueSetup method.



Main Queue setup warning

To remove this warning we simply have to implement specified method in our swift class and returns Boolean as below:
Now, it’s time to test our bridging code. Run your app and enter the password and click save password button.


After clicking the button, we passed the entered password text to our swift class where it is getting saved in the iOS keychain. On successful completion, we received call back with Boolean value in our React Native code. Here we  show alert to the user if password is saved successfully.
In this way we can call any code written in Swift from our React codebase to perform some operations which are not possible to implement in React Native

If you enjoyed reading this article🙂, then please don’t forget to share it with your friends and do subscribe this blog to receive more technical posts in future via email.

Comments

  1. Hi, I want to express my gratitude to you for sharing this fascinating information. It's amazing that we now have the ability to share our thoughts. Share such information with us through blogs and internet services
    Faceboo bellen

    ReplyDelete

Post a Comment

Popular posts from this blog

Lifecycle of React Native Component [2020 Edition]

What are the life cycle methods of React Native Component? A component's life cycle in React Native can be divided into 4 phases: React Native Component life cycle phases Mounting:  In this phase,  component instance is created and inserted into the DOM. Updating: In updating phase, a react component is said to be born and it start growing by receiving new updates. Unmounting: In this phase, a react component gets removed from actual DOM. Error Handling: It is called when any error occurs while rendering the component. Now let's discuss about different methods that gets called during these phases. Mounting phase Below are the methods which gets called when instance of component is created and inserted into the DOM. Constructor() static getDerivedStateFromProps() render() ComponentDidMount() Constructor() constructor ( props ) { super ( props ) ; this . state = { employeeId : 0 } ; } It is first method which gets called in the l

SOLID Design Principles in Swift

What are solid principles in programming world? 5 SOLID design principles in swift SOLID is acronym used in software programming for making software design more understandable, flexible, scalable and maintainable.  Every Software Developer must be aware of 5 SOLID principles in order to deliver good quality code SOLID stands for what? S -  Single Responsibility principle O - Open Closed Principle L - Liskov substitution Principle I - Interface segregation Principle D - Dependency Inversion Principle If we apply 5 SOLID principles while creating iOS/Mac Apps then the benefits which we will get are as follow: ·       We will have flexible code which can be changed easily. ·       Software code becomes more reusable. ·       Software developed will be robust, scalable and stable. ·       Code is loosely couple which means dependency between the elements is low. Now let’s discuss each principle one by one. 1.)  Single Responsibility Principl

What's new in iOS 13

Hi guys, Lets have a quick review on what new features Apple has released in its latest iOS 13 version. iOS 13 version iOS 13 makes old iPhone faster, last longer  - In iOS 13, Face ID unlocking will be 30% faster than before , app launch times are two times faster. Apple also found a way to make app downloads smaller, up to 60% on average. iOS 13 Dark Mode  - Apple introduced new dark mode option which changes the entire look of the operating system from light to dark. All native Apple apps feature Dark Mode support, and third-party apps can use Dark Mode APIs to add Dark Mode integration. iOS 13 features a QuickPath keyboard  - With iOS 13, Apple's default QuickType keyboard will be incorporating swipe-to-type, a popular way of sliding across the keyboard to form words. Before this, we have to use extensions like Google’s Gboard and SwiftKey Sign - In with Apple - Now, we can use Apple sign In to  conveniently sign in to third-party accounts.Sign-in with A