Swift Native Code in React Native

Why do we want to use native modules/code in react native ?
There are some scenarios where we need to use native code due to unsupported features by react native.
Okay, let’s get into the code !!!
Create a React Native App [ CLI Quick Start] :
~ npx react-native@latest init AwesomeProject
This above syntax will create a new react native project. If you facing any issue on installing process please have a look on this React Native Documentation
If you have any cocoapods to be install please follow these steps:
~ cd iOS
~ bundle install
~ bundle exec pod install
To run the newly created project, please follow below commands:
~ npm start
~ npm run ios
Create Custom Modules in Swift:
Navigate to the iOS folder and open the file name AwesomeProject.xcworkspace via xcode.
First we will create a swift file Addition.Swift and it will ask us to create an objective -c bridging header file. Click on Create Bridging Header
Then create a objective — c file with same name Addition.m
Here i will be adding few method which i will be calling inside react native code
Addition.Swift:
In this below code i have added one alert function which we will call this function inside our react native
import Foundation
import UIKit
@objc(Addition) class Addition : NSObject {
@objc func showAlert() {
let alert = UIAlertController(title: "Congratz !", message: "You have added native swift in to React Native", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if var topController = keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
DispatchQueue.main.async { [weak self] in
topController.present(alert, animated: true, completion: nil)
}
}
}
}
AwesomeProject-Bridging-Header.h:
#import <React/RCTBridgeModule.h>
Addition.m:
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(Addition, NSObject)
RCT_EXTERN_METHOD(showAlert)
@end
That’s it………
Now let’s call this native code into our react native . Open react native source code via visual studio and navigate to App.tsx file
App.tsx:
import { Button, NativeModules,} from ‘react-native’;
const {Addition} = NativeModules;
Here I have created one button name -> “Show Alert”. On tap of this button we will call our native code function to show alert
return (
<SafeAreaView style={{…styles.containerStyle,…backgroundStyle}}>
<Button title='Show Alert' onPress={() => Addition.showAlert()} />
</SafeAreaView>
);
Result :
After this , I was not able to compile from visual studio code due to some x84_64 architecture error.
~ npm run ios
But I was able to run the code from xcode. You can download this demo project from my GitHub Link
Read more about Native Modules