MAC从已有的IOS项目(swift)快速集成到RN.

2019-07-19  本文已影响0人  I_YoYo

前提环境已经OK,安装参考https://reactnative.cn/docs/getting-started/
集成已有项目到RN有两种方法

方法1:手动创建package.json, 使用命令npm install,再创建ios目录加入已有IOS项目,并在Podfile导入相应包并pod install安装(该方式会遇到各种坑)。
CocoaPods could not find compatible versions for pod "React/DevSupport":
CocoaPods could not find compatible versions for pod "React/Core":

方法2:使用$yarn add react-native 创建默认的RN项目,里面包含默认的IOS和Android项目。什么都配置好了,我们替换掉IOS项目(速度快,简单,不易出问题)。

========================= 方法2安装===================
参考:https://reactnative.cn/docs/getting-started/
1:创建个空文件夹(RN3),这个自己取名。
2:cd该目录执行  $react-native init AwesomeProject
3:cd到Podfile同级目录,使用$pod install 更新依赖包
(若中途更新失败则可重复pod update --verbose --no-repo-update)
初始化_下载相关文件 更新配置完成

二,把“ AwesomeProject”项目替换成自己要替换的项目

1:替换app.json文件中的“ AwesomeProject”名字;
2:打开项目导入CocoaPods更新的库 Build Phases -> Link Binary With Libraries
3:创建个桥接文件,导入头文件(swift项目新建一个oc文件时,xcode自动提示创建桥接文件)
#import <React/RCTRootView.h>
#import <React/RCTBundleURLProvider.h>
4:npm start 启动,并运行Xcode。
这时会提示UIViewControllerBasedStatusBarAppearance错误信息,只需按照提示plist里面该属性设置为NO即可

四,修改UIViewController,运行项目

///ViewController.swift
 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.present(RNViewController(), animated: true, completion: nil)
    }
//
//  Created by administrator on 2019/7/19.
//  Copyright © 2019 administrator. All rights reserved.
//

import UIKit
class RNViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "http://localhost:8081/index.bundle?platform=ios")!
        let rootView = RCTRootView(
            bundleURL: url,
            moduleName: "SwiftRNProject",//这里的名字要和app.json中相同
            initialProperties: nil,
            launchOptions: nil
        )
        view = rootView
    }
}

运行OK 文件目录

总结两种方式的区别:
第一种手动创建 index.js package.json等等,这些目录和方式二生成产生的文件有区别。
使用包管理工具yarn创建默认的RN项目,自动生成ios和android项目,基本可以保证最新配置和结构。

demo下载路径
有什么错误欢迎批评指正 。

上一篇 下一篇

猜你喜欢

热点阅读