LoginSignup
4
4

More than 5 years have passed since last update.

CocoaPodsでアプリ側ターゲットのbuild_settingsを変更する方法

Last updated at Posted at 2014-03-26

Xcodeで、End-to-End testsやIntegration testsを実行するときに、テスト時だけ行う処理とか逆に行わない処理とかを書きたいと思いますが、
メソッド差し替え等の手段を使えない場合、下記のようにマクロを定義しておかないと余計な処理が走って面倒なことになります。

#ifndef APP_TESTING
    // テスト以外のときだけ実行する処理
    // 広告SDKとかが勝手にブラウザへ飛ばす処理とか
#endif

CocoaPodsを使っていると、アプリ側のbuild_settingsのPreprocessor Macrosが書き換わるので
同時にアプリで使用するマクロも、podコマンドを実行したときに一緒に定義する方法ないかなと思って、
試した所うまく行ったのでメモ

post_installのブロックでworkspaceかなんかを参照する変数かなんかあるのかとおもっていたのですが、
どうやら、ないようなのでxcodeprojを使ってアプリ側のprojectを開いて変更すればいいようです

Podfile
TESTING_TARGETS = %w[AppTests AppIntegrationTests]
post_install do |installer|
  # アプリ側のxcode projectを開く
  Xcodeproj::Project.open('App.xcodeproj').tap do |project|
    targets = project.targets.find_all do |target|
      TESTING_TARGETS.include?(target.name)
    end
    # Test用macro定義
    targets.each do |target|
      target.build_configurations.each do |config|
        if config.name == "Debug"
          preprocessor_definitions = config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] || ['$(inherited)']
          preprocessor_definitions = [preprocessor_definitions] unless preprocessor_definitions.instance_of?(Array)
          preprocessor_definitions.push('APP_TESTING=1').uniq!

          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = preprocessor_definitions
        end
      end
    end

    project.save
  end
end
4
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4