在此之前,最好了解一下RN与OC直接的通信机制!
1.引入头文件
#import <RCTBridgeModule.h>
#import <RCTConvert.h>
#import <RCTEventDispatcher.h>
2.遵守协议<RCTBridgeModule>
3.向系统注册模块RCT_EXPORT_MODULE()宏(这个宏也可以添加一个参数用来指定在Javascript中访问这个模块的名字。如果你不指定,默认就会使用这个Objective-C类的名字。)
4.暴露模块方法RCT_EXPORT_METHOD(doSomething)
完整的代码如下:
.h文件
#import <Foundation/Foundation.h>
#import <RCTBridgeModule.h>
@interface RegistManager : UIViewController<RCTBridgeModule>
@end
.m文件
#import "RegistManager.h"
#import <RCTConvert.h>
#import <RCTEventDispatcher.h>
@interface RegistManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,RCTBridgeModule>
@end
@implementation RegistManager
RCT_EXPORT_MODULE();
//桥接到Javascript的方法返回值类型必须是void。React Native的桥接操作是异步的,所以要返回结果给Javascript,必须通过回调或者触发事件来进行
RCT_EXPORT_METHOD(openImagePicker)
{
[self showPhotoChooseSheetWithTitle:@"" message:@"选择头像"];
}
- (void)showPhotoChooseSheetWithTitle:( NSString *)title message:( NSString *)message {
//打开拍照
void(^cameraBlock)() = ^(){
UIImagePickerController *upc = [[UIImagePickerController alloc] init];
upc.videoQuality = UIImagePickerControllerQualityTypeMedium;
upc.delegate = self;
upc.allowsEditing = NO;
//拍照
upc.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:upc animated:YES completion:nil];
};
//系统相册
void(^photoBlock)() = ^(){
UIImagePickerController *upc = [[UIImagePickerController alloc] init];
upc.videoQuality = UIImagePickerControllerQualityTypeMedium;
upc.delegate = self;
upc.allowsEditing = NO;
//系统相册
upc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:upc animated:YES completion:nil];
};
NSArray *array = @[
@{@"拍摄":cameraBlock},
@{@"系统相册":photoBlock}
];
[self showAlertWithTitle:title message:message array:array cancleBlock:nil];
}
-(void)showAlertWithTitle:( NSString *)title message:( NSString *)message array:(NSArray <NSDictionary *>*)array cancleBlock:(void(^)())cancleBlock {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
for (NSDictionary *dict in array) {
NSString *actionTitle = [[dict allKeys] lastObject];
void(^sureBlock)() = [[[dict allValues] lastObject] isKindOfClass:[NSNumber class]] ? nil:[[dict allValues] lastObject];
[alertVC addAction:[UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
if (sureBlock) {
sureBlock();
}
}]];
}
[alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
if (cancleBlock) {
cancleBlock();
}
}]];
[self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:NO completion:^{
}];
}
.js文件中
模块类完成映射后,会在JS中生成一个模块对象RegistManager以供调用
var RegistManager = require('react-native').NativeModules.RegistManager;
var PersonInfo = React.createClass({
getInitialState(){
return {
avatarSource:null,
city:'',
trade:'',
major:'',
cityPick:false,
tradePick:false,
majorPick:false,
}
},
componentWillMount(){
console.log(this.props.userData)
},
render(){
return(
<View style={styles.getCodeBody}>
<NavBar backAction={()=>{
this.props.navigator.pop()
}}
title={'完善个人信息'}
leftImage={require('../images/Common/icon/button_return_white.png')}
rightItemTitle="跳过"
nextAction={()=>{
RegistManager.back();
}}/>
<ScrollView style={{flex:1}}>
{/*头像*/}
<View style={styles.pIconView}>
<TouchableWithoutFeedback onPress={()=>{
// js->oc
RegistManager.openImagePicker()
}}>
<Image
source={this.state.avatarSource?this.state.avatarSource:require('../images/Login/button_register_camera.png')}
style={styles.pIconImage}></Image>
</TouchableWithoutFeedback>
</View>
...
</ScrollView>
</View>
)
}
})
这样基本就完成了调用原生相册
但是一般都需要把选中的图片在传递给js去显示
熟悉两个block
5.void (^RCTPromiseResolveBlock)(id result)
6.void (^RCTPromiseRejectBlock)(NSString *code, NSString *message, NSError *error)
注意:这两个block要同时存在,不然会报错
7.把block保存下来,取到图片后调用回调
修改后:
.m文件
@interface RegistManager : UIViewController<RCTBridgeModule>
@property(nonatomic, strong) RCTPromiseResolveBlock resolve;
@end
@implementation RegistManager
RCT_EXPORT_METHOD(openImagePicker:(NSString *)userID
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
self.resolve = resolve;
[self showPhotoChooseSheetWithTitle:@"" message:@"选择头像"];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
CGSize size = {100, 100};
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
[[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, size} cornerRadius:0] addClip];
[image drawInRect:(CGRect){CGPointZero, size}];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImageJPEGRepresentation(result, 1.0f);
[data writeToFile:保存到本地地址 atomically:YES];
[picker dismissViewControllerAnimated:NO completion:^{
// 传给JS
self.resolve(保存到本地地址);
}];
}
@end
.js文件
RegistManager.openImagePicker(userData._id).then((data)=>{
this.setState({
avatarSource:{uri: data}
})
}).catch((err)=>{
console.log(err)
})