將RN工程嵌入到現(xiàn)有原生iOS應(yīng)用

今天心血來潮,就想嘗試一下將RN工程單獨嵌入到原生工程中,所以就做了嘗試,本文是通過cocopods集成RN到現(xiàn)有工程的,但是其中也遇到一個問題,怎么編譯都不過。

依賴包

React Native的植入過程同時需要React和React Native兩個node依賴包,所以需要我們創(chuàng)建package.json文件和正確的RN文件目錄結(jié)構(gòu)

對于一個典型的React Native項目來說,一般package.json和index.ios.js等文件會放在項目的根目錄下。而iOS相關(guān)的原生代碼會放在一個名為ios/的子目錄中,這里也同時放著你的Xcode項目文件(.xcodeproj)。

88161340-E7F4-46B0-86A9-5A13DCCDA819.png

按照上圖的目錄結(jié)構(gòu)創(chuàng)建

package.json

{
    "name": "TestReactNative",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0-alpha.6",
        "react-native": "0.44.3"
    },
    "devDependencies": {
        "babel-jest": "20.0.3",
        "babel-preset-react-native": "2.1.0",
        "jest": "20.0.4",
        "react-test-renderer": "16.0.0-alpha.6"
    },
    "jest": {
        "preset": "react-native"
    }
}

安裝依賴包

使用npm(node包管理器,Node package manager)來安裝React和React Native模塊。這些模塊會被安裝到項目根目錄下的node_modules/目錄中。 在包含有package.json文件的目錄(一般也就是項目根目錄)中運行下列命令來安裝:

npm install

新建index.ios.js

這個是隨便一個index.ios.js即可,我是從一個RN的初始化工程復(fù)制了一個出來

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class DemoApp extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('TestReactNative', () => DemoApp);

至此RN的相關(guān)依賴已經(jīng)配置好,接下來就該配置cocopods了

cocopods配置

1、創(chuàng)建Podfile,如果已經(jīng)有了可以忽略此步驟

##在iOS原生代碼所在的目錄中(也就是`.xcodeproj`文件所在的目錄)執(zhí)行:
$ pod init

Podfile文件內(nèi)容如下:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'TestReactNative' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for TestReactNative
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'DevSupport', # 如果RN版本 >= 0.43,則需要加入此行才能開啟開發(fā)者菜單
    'RCTText',
    'RCTNetwork',
    'RCTWebSocket', # 這個模塊是用于調(diào)試功能的
    # 在這里繼續(xù)添加你所需要的模塊
  ]
  # 如果你的RN版本 >= 0.42.0,請加入下面這行
  pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
end

subspecs就是你依賴的包。可用的subspec都列在node_modules/react-native/React.podspec
中,基本都是按其功能命名的。一般來說你首先需要添加Core,這一subspec包含了必須的AppRegistry、StyleSheet、View以及其他的一些React Native核心庫。如果你想使用React Native的Text庫(即<Text>組件),那就需要添加RCTText的subspec。同理,Image需加入RCTImage,等等。
2、安裝依賴包
執(zhí)行pod install

C07B6B3E-1642-4EAC-9814-BE6A55C4527C.png

會看到以上過程則表示安裝依賴已經(jīng)成功
3、調(diào)用RN工程

#import "ViewController.h"
#import <React/RCTRootView.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)actionClick:(id)sender {
    NSLog(@"High Score Button Pressed");
    NSURL *jsCodeLocation = [NSURL
                             URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL : jsCodeLocation
                         moduleName        : @"TestReactNative"
                         initialProperties :nil
                          launchOptions    : nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

至此整集成已經(jīng)結(jié)束,可以直接運行xcode過程,或者通過命令運行工程

# From the root of your project, where the `node_modules` directory is located.
$ npm start
# 在項目的根目錄中執(zhí)行:
$ react-native run-ios

不知道大家有沒有注意我們package.json中react-native中的版本是"0.44.3",而為什么不是最新版46的呢??這就是一個很大的坑!從45版本開始RN有4個文件被墻了,所以如果大于44版本的react-native會一直編譯不過
有以下3個解決方案:
1、不導(dǎo)入最新的包,導(dǎo)入44版本
2、翻墻唄。。。。
3、下載被墻的4個依賴包,手工導(dǎo)入

優(yōu)化加載速度

在原生調(diào)用RN的時候有點慢。大家在集成的時候會發(fā)現(xiàn)加載的過程挺慢的,可以壓縮加載本地文件,這樣加載就快了。通常我們可以將文件放到服務(wù)器上,然后通過IP地址來加載,這種方式其實也是比較慢的,最好的方式就是將文件提前下載到本地,通過一定的更新機制確保本地文件時最新的,通過使用這種方式加載就很快了。

  • 到當(dāng)前項目的根目錄中執(zhí)行:
react-native bundle --platform ios --dev false --entry-file index.ios.js --bundle-output ios/main.jsbundle
  • 將main.jsbundle加載到Xcode工程中,然后通過以下方式獲取URL地址來加載
NSString *path = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"jsbundle"];
NSURL *jsCodeLocation = [NSURL URLWithString:path];

如果大家在這個過程還有不明白的可以留言給我,我將盡最大努力給大家解決的哦

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容