RN嵌入到现有iOS原生应用

作者: JackChen__ | 来源:发表于2016-10-15 22:18 被阅读5104次

第一步 环境配置

注意:

  1. xcode可以正常编写程序并运行;
  2. 会使用终端。
  3. 读者需要根据上下文理解本文运行的终端命令所在的目录
  4. iOS工程根目录:.xcodeproj文件所在的目录;根目录:将要整合成的整个工程的目录(本文的根目录是指ios/目录的父目录)
  5. 此文中的demo来子官方网站

1.安装cocoapods

打开终端,执行以下命令

sudo gem install cocoapods

此步需要安装一些其他程序,比如我的需要安装2.2.2版本以上的ruby brew install ruby 。读者可以根据实际情况安装所需程序。

2.添加package.json文件

cd 到iOS工程根目录,执行以下命令,然后编辑package.json,最后保存

vim package.json

一般package.json文件包含以下内容

{
  "name": "NumberTileGame",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "15.0.2",
    "react-native": "0.26.1"
  }
}

此处的"name": "NumberTileGame",NumberTileGame替换成自己的iOS工程名

创建完package.json文件后,建议将原生的iOS工程文件放到新建的ios/目录下

3.安装node_modules/

cd到根目录,执行以下命令

npm install

此步会根据上面的package.json文件安装node_modules

第二步 React Native Framework

Subspecs介绍

使用rn开发App并不是所有的rn框架都必须使用,而Subspecs为我们提供了选择,通过Subspecs列表我们可以进行框架选择。说白了,就是Subspecs就是菜单,吃哪些菜点哪些菜。

例如想要用到AppRegistry, StyleSheet, View和其他的rn核心包,需要导入Core subspec;Text组件需要导入RCTText subspec; Image组件需要导入RCTImage subspec。这些配置需要在下面的Podfile中设置

node_modules/react-native/React.podspec。此文件中声明了react-native框架的各种包。

创建Podfile文件

cd到iOS工程的根目录(ios/)

pod init

命令执行完后会在(ios/)目录下创建Podfile文件,所需要的react-native依赖库在这里配置,初始内容如下:

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

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

  # Pods for NumberTileGame

  target 'NumberTileGameTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'NumberTileGameUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

Pod安装

对Podfile进行修改,根据需要的组件进行配置。如下:

# The target name is most likely the name of your project.
target 'NumberTileGame' do

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'RCTText',
    'RCTWebSocket', # needed for debugging
    # Add any other subspecs you want to use in your project
  ]

end

ios/目录下,执行以下命令

pod install

这一步会等待很长时间,要有耐心。(主要是网络问题,可以从网上搜索解决办法)

创建index.ios.js (rn的入口函数)

cd到根目录,执行以下命令

touch index.ios.js

编写index.ios.js 如下

'use strict';

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

class RNHighScores extends React.Component {
  render() {
    var contents = this.props["scores"].map(
      score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text>
    );
    return (
      <View style={styles.container}>
        <Text style={styles.highScoresTitle}>
          2048 High Scores!
        </Text>
        <Text style={styles.scores}>
          {contents}
        </Text>
      </View>
    );
  }
}

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

// Module name
AppRegistry.registerComponent('RNHighScores', () => RNHighScores);

此处最后一行代码中的RNHighScores是自定义的rn组件的名字,iOS原声代码调用时需要用到

第三步 编写iOS代码调用rn

此步可能还有其它方法,请自行查询资料
使用xcode打开源代码时一定要打开 .xcworkspace 文件,若果直接打开 .xcodeproj 会出现链接错误

打开工程后,左侧导航栏如下图所示

1.png

iOS源码

ViewController.m

#import "ViewController.h"
#import "RCTRootView.h"

@interface ViewController ()

@end

@implementation ViewController

![2.png](http:https://img.haomeiwen.com/i3170699/5debf45bf79aedcb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

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

- (IBAction)highScoreButtonPressed:(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        : @"RNHighScores"
                         initialProperties :
     @{
       @"scores" : @[
               @{
                   @"name" : @"Alex",
                   @"value": @"42"
                   },
               @{
                   @"name" : @"Joel",
                   @"value": @"10"
                   }
               ]
       }
                          launchOptions    : nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

@end

连线

  1. 在mainboard中创建两个UIButton,如下图所示
  2. High Scores UIButton与 - (IBAction)highScoreButtonPressed:(id)sender 方法连线,连线时选择 Touch Up Inside ,如下图所示
2.png

测试

Apple默认会阻止程序访问http,需要修改info.plis配置,如下图所示

3.png

此时如果运行,可能会报以下错误

4.png

解决此问题需要导入 libc++.tbd 依赖包,如下图所示

5.png

最后,command + r 运行程序

至此,rn整合iOS项目的环境配置已经基本完成,可以愉快的敲代码了!可是事与愿违,在我修改代码的时候发现xcode并不支持rn依赖库的代码补全,后来从网上找到了解决方法

demo

相关文章

网友评论

  • 鹏雨燕:如果我想加一个额外的subspec,如react-navigation,在cocoapods该怎么写
  • 36759be74e7d:node_modules 这个放在项目里,这个太大了,怎么处理?
  • youth_H:我在pod install的时候出现这样的错误:
    [!] Unable to satisfy the following requirements:

    - `React/Core (from `../node_modules/react-native`)` required by `Podfile`

    It seems like you've changed the constraints of dependency `React/Core` inside your development pod `React/Core`.
    You should run `pod update React/Core` to apply changes you've made.

    麻烦楼主帮忙解答一下
    lee_moons:podfile版本低于项目版本
  • seasa:感谢楼主的无私奉献,十分有用,深表感谢
  • 含泪若笑:你好 我的会报错
    10:9: 'RCTRootView.h' file not found
    不知道为什么,
    求帮忙
    Yohohoho:#import <React/RCTRootView.h>
    母鸡啊:Undefined symbols for architecture x86_64:
    "_OBJC_CLASS_$_RCTRootView", referenced from:
    objc-class-ref in
    seasa:你需要在根目论上npm install ,同时使用Cocoapods导入相应的类

本文标题:RN嵌入到现有iOS原生应用

本文链接:https://www.haomeiwen.com/subject/prkoyttx.html