首页 > 解决方案 > 使用 Podfile post_install 钩子添加自定义构建规则

问题描述

我有一个需要一些自定义构建规则才能正常工作的 Cocoapod。

在我看来,没有办法在 podspec 中添加任何自定义构建规则,但也许有办法在 Podfile 中使用 post_install 挂钩?

标签: swiftcocoapods

解决方案


我最终能够得到这个工作。我编写了一个使用 Xcodeproj gem 的 ruby​​ 函数(可在 Podfile 中使用。)

def add_build_rule(target_name, project)
  new_rule = project.new(Xcodeproj::Project::Object::PBXBuildRule)

  project.targets.each do |target|
    if target.name == target_name
      if target.build_rules.count != 0
        puts "#{target.name} already has a build rule."
        return
      end
      puts "Updating #{target.name} rules"

      new_rule.name = 'My Custom Rule'
      new_rule.compiler_spec = 'com.apple.compilers.proxy.script'
      new_rule.file_patterns = 'myFile.whatever'
      new_rule.file_type = 'pattern.proxy'
      new_rule.is_editable = '1'
      new_rule.output_files = []
      new_rule.input_files = []
      new_rule.output_files_compiler_flags = []
      new_rule.script = "echo Hello World"
      target.build_rules.append(new_rule)
    end
  end

  project.objects_by_uuid[new_rule.uuid] = new_rule
  project.save()
end

然后在我的 podfile 中我添加了这个 post_install 钩子。

post_install do |installer|
    add_build_rule("MyTarget", installer.pods_project)
end

推荐阅读