Native Modules: React Native to Swift for beginners.
In this article, I will show you the simplest way to pass the data from React Native to Swift. If you are a newbie, working in mobile development for the first time, this article is absolutely written for you.
1. Create a new react native app, open your terminal and run:
npx react-native init NativeModules
2. Open Xcode and navigate to NativeModules/ios/NativeModule.xcworkspace
3. Create a swift file and name it ‘RN_to_Swift.swift’
When creating a new swift file, Xcode will ask us to create a ‘Bridging Header ’ file, this file will connect the swift file to the Objective C file (we will make it in the next step).
In the ‘RN_to_Swift.swift’ file, we will create a class ‘RN_to_Swift’ and define this class as NSObject which will connect to the Objective C file (we create it in the next step), using ‘@objc(RN_to_Swift)’. Now, see what we have:
4. Write the function to get the data input on React Native side
Open your application on VSCode and write a simple code, input data and display it
Let’s run the application, open the terminal and run:
npm run ios
or click the run button on Xcode
You can imagine that when you work on a flexible project, your task is working on the Swift side but you need to get the data from your partner on React Native side. For instance, user’s information like password, email…
In this case, we need to get the data input (“Wynne Tran”) and display it on the Swift side.
5. Write a function to get data sent from React Native side
Go back to Xcode and open the “NativeModules-Bridging-Header.h” file, adding “#import <React/RCTBridgeModule.h>”
Open the “RN_to_Swift.swift” file, write a “Call Back” function to get the data from React Native side
6. Create an Objective C file to export the swift function.
Create the “RN_to_Swift.m” file and export the swift class
7. Connect Swift function to React Native
And we are done, let's run the application again, we will see the data input will display on the Swift side.
Thank you for reading this article. If you found it useful, please click a clap to inspire me to keep sharing knowledge with you.