DEV Community

Calin Tamas
Calin Tamas

Posted on

Add header to Header Search Paths via cocoapods

If at some point - for some weird reason - you need to append some new headers to your current Header Search Paths, you can write something along these lines:

def append_header_search_path(target, path)
    target.build_configurations.each do |config|
        xcconfig_path = config.base_configuration_reference.real_path

        # a positive lookbehind regular expression (?<=)
        # to keep the delimiter at the end of each string:
        file_data = File.read(xcconfig_path).split(/(?<=[\S])\n/)

        # Copy current headers
        header_search_paths = ""
        header_search_paths_index = nil
        file_data.select.with_index do |val, index|
          if /HEADER_SEARCH_PATHS/ =~ val
            header_search_paths = val
            header_search_paths_index = index
          end
        end

        # Append the new header
        new_header_search_paths = header_search_paths << " #{path}"
        file_data[header_search_paths_index] = new_header_search_paths

        # Write it back to the file
        file_data = file_data.join("\n")
        File.write(xcconfig_path, file_data)
    end
end

Then, you can use it in a post-install action:

post_install do |installer|
    installer.pods_project.targets.each do |target|
      if target.name == "AnyProject"
          puts "Updating #{target.name} HEADER_SEARCH_PATHS"
          append_header_search_path(target, "${PODS_ROOT}/../new_header")
      end
    end
  end

Top comments (0)