Create ReactNative Modules with Swift

1. Open the xcode project file in the ios folder of the react-native project.
2. Create a Swift class that needs to be exposed to ReactNative at the level of AppDelegate.m


 
Name it "MyModule"


 
After the creation, you will be prompted whether to create a Bridging Header, because if IOS development requires coexistence of swift and oc, Swift must provide a Bridging Header to oc, otherwise oc cannot call Swift. Currently Swift cannot be directly exposed to ReactNative, so oc is needed for bridging.


 
3. Add a line of code to the Bridging Header file you just created, which is the header file of React Bridge
 
#import "RCTBridgeModule.h"
 
4. Write our main class file, which is MyModule.swift just created
import Foundation
//Add @objc to let swift and oc be called
@objc(MyModule)
class MyModule: NSObject {
  @objcfunc sayHi(msg:String!, callback: RCTResponseSenderBlock) -> Void {
    callback(["Swift Module recieved your message, content is \"\(msg)\""]);
  }
}
 
5. The last step is to expose our module method through ReactNative. This step is still done in the oc implementation file, and a new MyModule.m file is created.


 
The code content is as follows:
// MyModule.m
#import "RCTBridgeModule.h"
@interfaceRCT_EXTERN_MODULE(MyModule, NSObject)
RCT_EXTERN_METHOD(sayHi:(NSString)msg callback:(RCTResponseSenderBlock)callback)
@end
 
5. At this point, the development of a Swift ReactNative module has been completed. Run it in XCode (Command + R), and after compiling the module, you can go to ReactNative to reference this module.
6. The modules and methods exposed by the Native language to ReactNative are all on the NativeModules module, so we create a new js module
import React, {
  NativeModules
} from 'react-native';
export default NativeModules.MyModule;
 
7. Apply this module in the business code and call the swift method
import MyModule  from './MyModule';

MyModule.sayHi("Hi, I am from JS” , (msg)=>{
  console.log(msg);
});)
 It will eventually output in the browser's console: Swift Module recieved your message, content is "I am from JS 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326730244&siteId=291194637