Flutter混合开发-Ruby脚本自动化集成Frameworks

西门桃桃 2021-08-22 PM 1479℃ 0条

背景简介

由于公司计划将技术栈由纯Native转为纯Flutter开发,但是以前的项目是纯原生项目,所以中间需要经历一段 Flutter 与 Native 混合开发的过程。

Flutter集成进已有项目有 CocoaPods+Flutter SDK 集成与 Embed frameworks 集成 两种方式,为了方便团队中未安装Flutter环境的小伙伴正常使用我们的项目,所以我们选择了第二种方式。

Embed frameworks 集成方式步骤极为繁琐,所以我整理了一个Ruby脚本用来自动化执行这些操作。

Ruby脚本源码


# coding: utf-8 

require 'fileutils'
require 'xcodeproj'

Flutter_DIR = "这里写Flutter项目的根目录"
TARGET_DIR = "这里写原生项目保存Flutter生成的Frameworks的目录"
PROJECT_DIR = "这里写 .xcodeproj 文件的目录"

SOURCE_DIR = Flutter_DIR+"build/ios/Release-iphoneos/"

# 1、生成framework
FileUtils.cd(Flutter_DIR) do
  system('flutter pub get')# 'flutter pub get'获取最新依赖库
  system('flutter build ios --release --no-codesign') #flutter build ios --debug 如果需要生成debug版本的frameworks就使用这个命令
end

puts "1、framework生成成功!"

# 2、复制framework到指定文件夹
Dir_paths = Dir.glob(SOURCE_DIR+"**/*.framework").reject { |file| file.match?("Runner") }

# 记录现存framework
Exist_Frameworks = []
Dir.glob(TARGET_DIR+'*').each do |file_path|
  Exist_Frameworks.push(File.basename(file_path))
end

# FileUtils.rm_r(TARGET_DIR) #删除文件夹
FileUtils.rm_rf(Dir.glob(TARGET_DIR+'*'))#删除文件夹中的内容

Dir_paths.each do |file_path|
  puts file_path
  FileUtils.cp_r(file_path, TARGET_DIR+File.basename(file_path))
end

puts "2、framework复制到工程指定目录成功!"

# 3、找出新增的Framework 然后添加引用 设置codesign

New_Frameworks = []
Dir_paths.each do |file_path|
  New_Frameworks.push(File.basename(file_path))
end

Redundant_Frameworks = New_Frameworks - Exist_Frameworks # 新增的Framework

if Redundant_Frameworks.count == 0
  puts "科科,没有新增的Frameworks喔"
else
  puts "注意:新增了#{Redundant_Frameworks.count}个Frameworks:"
  puts Redundant_Frameworks
  
  Framework_paths = []
  Redundant_Frameworks.each do |file_name|
    Framework_paths.push(TARGET_DIR+file_name)
  end

  # 打开项目工程 给新增的framework添加引用
  project = Xcodeproj::Project.open(PROJECT_DIR)

  # 找到每个target增加引用
  targetIndex = 0
  project.targets.each_with_index do |target, index|
    if target.name.include?('Test')
      # puts "index: #{index} : #{target} 测试工程 不管它"
    else
      puts "target:#{target} "
      Framework_paths.each do |file_path|
        puts file_path
        # 1、创建framework文件引用
        file_ref = project.frameworks_group.new_file(file_path)
        target.copy_files_build_phases.each do |item|
          if item.name == "Embed Frameworks"
             item.add_file_reference(file_ref)
             item.dst_subfolder_spec = "10"
          end
        end
      end
    end
  end

  project.save
  puts "pbxproj文件已保存!"
end

使用

将代码复制到文本文件中,修改路径后,另存为abc.rb文件,然后终端运行 ruby abc.rb即可。

标签: Ruby

非特殊说明,本博所有文章均为博主原创。

评论啦~