React native learning: encapsulation and calling of iOS native modules, reactios

Source: Internet
Author: User

React native learning: encapsulation and calling of iOS native modules, reactios
1. Preface

The previous article introduced how to encapsulate Android native modules. Today, we will introduce how to encapsulate ios native modules for React native calls. In React Native, the Native module of the ios platform is an Objective-C class that implements the RCTBridgeModule Protocol. In this example, the RDBMS is the abbreviation of ReaCT. Some Objective-C code is involved here, but don't worry. It is certainly better to have a certain degree of ios development foundation. If you have never touched on Objective-C before, some syntaxes may be difficult to understand, but this does not prevent reading. This article uses the most classic HelloWorld instance in the programming world to introduce the encapsulation of ios native modules. However, if you want to encapsulate more complex native ios platform modules in the future, you must master the syntax of Objective-C or Swift.

2. Create a module class

In.. \ ExerciseProject \ ios \ ExerciseProject directory to create a new HelloWorld. h and HelloWorl. m file, or open it using Xcode.. \ ExerciseProject \ ios \ ExerciseProject. xcodeproj file, new HelloWorld class, will automatically generate HelloWorld. h and HelloWorl. m files .. The h header file contains the class interface, which implements specific functions. First look at HelloWorld. h:

#import  @interface HelloWorld : NSObject  @end  

The header file RCTBridgeModule. h is imported here. RCTBridgeModule is a bridge implementation provided by React Native for Native Communication with iOS. The HelloWorld class is defined to inherit from NSObject and the RCTBridgeModule interface is implemented.

Let's take a look at HelloWorld. m:

#import "HelloWorld.h"#import "RCTLog.h"@implementation HelloWorldRCT_EXPORT_MODULE();RCT_EXPORT_METHOD(hello:(NSString *)name){ RCTLogInfo(@"Hello %@ from IOS", name);}@end

The first line imports the corresponding. h file. Because you need to use RCTLogInfo to output the log to the application, RCTLog. h is imported here. @ Implementation and @ end are the specific implementation of HelloWorld. Use the RCT_EXPORT_MODULE () macro to export this Native module for the React Native Interface to call, while the RCT_EXPORT_METHOD () macro to implement the method to be used for Javascript.

3. Use in javascript

To make the encapsulated module easy to use in JavaScript, the native module is usually encapsulated into a JavaScript module. This saves the trouble of adding NativeModules to each access component. However, this step is not required.
In this example\ ExerciseProject \ src \ 12_nativeapi \ create a new HelloWorldIOS. js File

let { NativeModules } = require('react-native');module.exports = NativeModules.HelloWorld;

In other JavaScript file code, you can access it as follows:

import HelloWorldIOS from './HelloWorldIOS';...HelloWorldIOS.hello('Jack');

The code for calling a method in a JavaScript file is as follows:

import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View,} from 'react-native';import HelloWorldIOS from './HelloWorldIOS';export default class HelloWorldIOSDemo extends Component { onPress(){ HelloWorldIOS.hello('Jack'); } render() { return (   ); }} 
4. Parameter type description

In the above example, we have passed in the string type parameter. in actual application, we may also need various types of parameters. RCT_EXPORT_METHOD supports all standard JSON types. The details are as follows:

String (NSString) number (NSInteger, float, double, CGFloat, NSNumber) boolean (BOOL, NSNumber) array (NSArray) contains any type of object (NSDictionary) in this list) function (RCTResponseSenderBlock) that contains keys of the string type and values of any type in the list)

In addition, any types supported by the RCTConvert class can also be used. RCTConvert is a type conversion library provided by React Native. For example, there is no time type in the supported types mentioned above. If we need to pass the time, we can use RCTConvert for type conversion.

The use of RCTConvert can be seen in the following example:
Steps are as follows: Create DateIOS. h

#import  #import  @interface DateIOS : NSObject  @end   

Create DateIOS. m

#import "DateIOS.h"@implementation DateIOSRCT_EXPORT_MODULE();RCT_REMAP_METHOD(compareDate, date1:(nonnull NSNumber *)d1 date2:(nonnull NSNumber *)d2){ NSDate* dt1 = [RCTConvert NSDate:d1]; NSDate* dt2 = [RCTConvert NSDate:d2]; NSComparisonResult result = [dt1 compare:dt2]; switch(result){ case NSOrderedAscending: { NSLog(@"compare result %@",@"start time < end time"); } case NSOrderedDescending: { NSLog(@"compare result %@",@"start time > end time"); } }}@end

Use in javascript

import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View, Button, DatePickerIOS, NativeModules} from 'react-native';export default class DateIOSDemo extends Component { constructor(){ super(); this.state = {startDate: new Date(), endDate: new Date()}; } onPressDateCompare() { let dateCompare = NativeModules.DateIOS; dateCompare.printDate(this.state.startDate.getTime(), this.state.endDate.getTime()); } onStartDateChange(date) { this.setState({startDate: date}); } onEndDateChange(date) { this.setState({endDate: date}); } render() { return (     ); }}   

In the above example, because the Date object cannot be transferred in the bridge channel, you need to convert the Date to a string or number for transmission. On ios, perform the conversion as follows:

NSDate* dt1 = [RCTConvert NSDate:d1];

On the javascript end, the date is passed in unix timestamp format:

 let dateCompare = NativeModules.DateIOS; dateCompare.printDate(this.state.startDate.getTime(), this.state.endDate.getTime());

It can also be passed in the form of a ISO-8601 string:

 let dateCompare = NativeModules.DateIOS; dateCompare.printDate(this.state.startDate.toISOString(), this.state.endDate.toISOString());

Both methods are converted to the correct NSDate type. However, if an invalid value is provided, for example, an Array, the program reports an error.

The above is a brief introduction to the encapsulation and call of the iOS native module.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.