要求:
1、熟悉Xcode编程
2、了解终端常用命令
3、会用CocoaPods做iOS程序的依赖管理
第一步:开发环境搭建
1、CocoaPods的安装,如果已安装完,直接跳过该步骤。
2、搭建RN开发环境,如果已经搭建好,直接跳过该步骤。
第二步:把React Native组件嵌入到iOS
1、设置项目目录结构
打开现有的iOS项目,在其中创建一个/ios子目录;然后将根目录中所有的iOS文件都拷贝到 /ios 子目录中。

2、安装JavaScript依赖包
2.1、创建安装依赖包文件package.json
打开终端,cd到根目录,执行命令
$ npm init
跟着提示一步步执行,主要设置的是名字(name 不支持大写)和版本,其他默认或者不输入。

执行成功之后会看到基本的json样式,可以在根目录中看到创建成功的package.json文件。

2.2、配置安装依赖包文件package.json
按下图红色区域方式配置package.json文件。
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},

2.3、添加JS环境
使用终端,cd到根目录,执行下面的命令
$ npm install --save react
$ npm install --save react-native
2.4、报错处理
执行完,可能会出现下图中的报错信息。

报错信息1:
npm WARN react-native@0.55.4 requires a peer of react@16.3.1 but none is installed. You must install peer dependencies yourself.
解决方案:执行命令
$ npm install --save react@16.3.1
报错信息2:
npm WARN eslint-plugin-react-native@3.2.1 requires a peer of eslint@^3.17.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
解决方案:Xcode方式打开package.json文件,添加如下两行,然后回到终端,执行命令
$ npm install

补充:dependencies中的react和react-native的版本取决于你的具体需求,推荐使用最新版本。可以使用下面的命令查看当前的最新版本。
$ npm info react
$ npm info react-native
成功安装JavaScript依赖包,会看到根目录多了2个文件。

3、创建Podfile文件
3.1、创建Podfile
终端cd到/ios子目录, 执行下面命令
$ pod init

3.2、配置Podfile
# Uncomment the next line to define a global platform for your project
# 别忘了把这里的注释去掉
platform :ios, '9.0'
# target的名字一般与你的项目名字相同
target 'RNInsertApp' do
# 'node_modules'目录一般位于根目录中
# 但是如果你的结构不同,那你就要根据实际路径修改下面的':path'
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'CxxBridge',
'DevSupport',
'RCTText',
'RCTNetwork',
'RCTWebSocket',
]
# 如果你的RN版本 >= 0.42.0,则加入下面这行
pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
# 如果RN版本 >= 0.45则加入下面三个第三方编译依赖
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
end

3.3、安装React Native的pod包
创建好了Podfile后,就可以开始安装React Native的pod包了。执行命令
$ pod install

4、index.js文件(rn的入口函数)
4.1、创建index.js文件
终端cd到根目录, 执行下面命令
$ touch index.js

4.2、添加你自己的React Native代码

5、编写代码调用RN
打开/ios子目录中的".xcworkspace",编写调用RN代码。

6、配置info.plist
Apple默认会阻止读取不安全的HTTP链接,我们需要把本地运行的Packager服务添加到info.plist中,以便能正常访问Packager服务。
NSAppTransportSecurity
NSExceptionDomains
localhost
NSTemporaryExceptionAllowsInsecureHTTPLoads

7、运行Package
运行Package,启动开发服务器。终端cd到项目根目录中, 执行下面命令
$ npm start

8、运行应用
打开/ios子目录中的".xcworkspace",运行应用。

项目源码
参考博客
网友评论