在iOS中创建React-Native页面,并跳转到原生页面

来源:互联网 发布:微软软件license模式 编辑:程序博客网 时间:2024/06/11 07:49

需求:

    上一篇文章中,我们讲到怎么在iOS原生里面集成React-Native,这篇文章将讲解怎么在原生中创建React-Native页面,并且从RN页面跳转到原生页面。
我将项目更新到了github上,里面有很多我自己的理解,希望可以帮到各位读者(react-native-learn)

http://www.jianshu.com/p/ffe9e8b8dbe6

[https://github.com/RabbitBell/react-native-learn]

创建:

    我们将在项目中创建一个View,用来展示React-Native页面

  • 在原生ios应用添加容器视图 我们在工程文件下创建一个名为ReactView的UIView文件: React-iOS目录 -> 右键 -> New File -> Cocoa Touch Class -> ReactView

ReactView.png
  • 修改ReactView.m
#import "ReactView.h"#import <RCTRootView.h>@implementation ReactView- (instancetype)initWithFrame:(CGRect)frame{    if (self = [super initWithFrame:frame]) {        NSString * strUrl = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true";        NSURL * jsCodeLocation = [NSURL URLWithString:strUrl];        // 这里的moduleName一定要和下面的index.ios.js里面的注册一样        RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation                                                             moduleName:@"ReactiOS"                                                      initialProperties:nil                                                          launchOptions:nil];        [self addSubview:rootView];        rootView.frame = self.bounds;    }    return self;}@end

ReactView.m中通过http://localhost:8081/index.ios.bundle?platform=ios&dev=true加载bundle文件,由RCTRootView解析转化原生的UIView,然后通过initWithFrame将frame暴露出去。

  • 在原生ios应用中引用ReactView 上面我们创建了一个ReactView,打开ViewController.m,在viewDidLoad方法中应用我们的ReactView。

    #import "ViewController.h"#import "ReactView.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    ReactView * reactView = [[ReactView alloc] initWithFrame:CGRectMake(0,64,CGRectGetWidth(self.view.bounds), 100)];    [self.view addSubview:reactView];}

    这样,我们的项目就创建好了。接下来就是运行项目了

    运行:

    如果做过reactNative开发,都知道每次运行项目之前都需要启动开发服务器,只不过之前是X-Code自动启动,现在需要手动开启。
    进入reactnative根目录(我是放在桌面上了,最简单的方式就是直接拖拽),然后启动$ react-native start


开启服务器.png

设置允许Http请求:

直接运行项目会报Could not connect to development server错误
解决方式:打开info.plist文件,添加下面配置即可:

<key>NSAppTransportSecurity</key>  <dict>      <key>NSExceptionDomains</key>    <dict>        <key>localhost</key>        <dict>            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>            <true/>        </dict>    </dict></dict>

运行ios项目:

通过Xcode点击项目或者command + R运行项目,如果顺利的话,就会看到成功运行的界面:


运行成功.png

当看到上面的图片,就代表大功告成,这样就掌握了在iOS原生中集成React-Native方法了~

跳转:

接下来,我们讲讲怎么从上面创建的RN页面点击Hello World !跳转回原生页面
ps:官方文档对于iOS和原生的交互写了好多,不知道你们看懂没,反正我是一头雾水。
还是直接上代码:

  • 在OC中的代码
     1. 在XCode 中的AppDelegate.h中创建原生的UINavigationController,这样在其他页面可以用过AppDelegate这个单例来调用到导航进行跳转操作
#import <UIKit/UIKit.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;// 创建一个原生的导航条@property (nonatomic, strong) UINavigationController *nav;@end

    2.在AppDelegate.m中使导航条成为跟控制器

#import "AppDelegate.h"#import "ViewController.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];    self.window.backgroundColor = [UIColor whiteColor];        ViewController *view = [[ViewController alloc]init];    // 初始化Nav    _nav = [[UINavigationController alloc]initWithRootViewController:view];    // 将Nav设置为根视图    self.window.rootViewController = _nav;        [self.window makeKeyAndVisible];        return YES;}

    3.新建 RCTModules 类,继承 NSObject 封装一个方法使用“通知”进行消息的传送从而实现页面的跳转

RCTModules.h

#import <Foundation/Foundation.h>#import "RCTBridgeModule.h"@interface RTModule : NSObject<RCTBridgeModule>@end

RCTModules.m

#import "RTModule.h"#import "RCTBridge.h"@implementation RTModuleRCT_EXPORT_MODULE(RTModule)//RN跳转原生界面RCT_EXPORT_METHOD(RNOpenOneVC:(NSString *)msg){    NSLog(@"RN传入原生界面的数据为:%@",msg);    //主要这里必须使用主线程发送,不然有可能失效    dispatch_async(dispatch_get_main_queue(), ^{        [[NSNotificationCenter defaultCenter]postNotificationName:@"RNOpenOneVC" object:nil];    });}@end

    4.接下来在ViewController.m中添加通知的方法

#import "ViewController.h"#import "ReactView.h"#import "AppDelegate.h"#import "OneViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.navigationItem.title = @"我是包含RN的原生页面哟~";    ReactView * reactView = [[ReactView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), 100)];    [self.view addSubview:reactView];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doPushNotification:) name:@"RNOpenOneVC" object:nil];}- (void)doPushNotification:(NSNotification *)notification{    NSLog(@"成功收到===>通知");    OneViewController *one = [[OneViewController alloc]init];    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];    [app.nav pushViewController:one animated:YES];    //注意不能在这里移除通知否则pus进去后有pop失效}@end

    5.接下来就要创建我们将要跳转的页面啦。创建OneViewController继承于UIViewController


OC中的项目结构.png
  • 在index.ios.js中的代码
    import React, { Component } from 'react';import {    AppRegistry,   StyleSheet,    Text,    View,   TouchableOpacity,    NativeModules} from 'react-native';var RNModules = NativeModules.RTModule;class ReactiOS extends Component {  render() {         return (                <View style={styles.container}>          <TouchableOpacity             onPress={()=>RNModules.RNOpenOneVC('测试')}>                 <Text>Hello World!</Text>          </TouchableOpacity>      </View>    );    }}const styles = StyleSheet.create({ container: {  backgroundColor : 'red',  height:100,  flexDirection : 'row'  },});AppRegistry.registerComponent('ReactiOS', () => ReactiOS);

    运行:

    上面的那些步骤写完,开启服务器就应该能看到下面这张图,点击helloWorld,跳转到下一个页面啦~

控制台打印.png

gif5新文件.gif

小结:

通过React-Native与iOS原生的集成步骤和这篇文章,应该能够学会怎么在项目中集成React-Native项目了。当然,你如果想在同一个RN页面中跳转多个页面,可以注册不同的通知,在RN页面点击的时候跳转就可以了。在我的demo中会有这个例子。
ps:我还是很推荐用Cocoapods集成React-Native开发环境的,因为我手动集成的时候遇到了好多坑,如果在开发中遇到什么其他问题,欢迎评论。
/(ㄒoㄒ)/~~ 不知道怎么往github上传。。。所以打包成了百度云

0 0
原创粉丝点击