Before we proceed to multi-environment configuration, we need to do some understanding of the composition of elements within Xcode.

  • Project: contains all the code, resource files and other information of the Project.
  • Target: The specific build of the specified code and resource files.
  • Scheme: Configures the environment for the specified Target.

There are three modes for configuring multiple environments

Method 1. Multiple targets

Create a new Target, change the BundleId, and change the info-plist file name generated with the Target

For OC, different environments for different targets are distinguished by the Macros that target defines in the Preprocessor Macros of Builed Setting

After switching different target compilation schemes, use them in code as follows

For Swift, you can configure a variable in Other Swift Flags in Builed Setting and determine it in swift code

However, this method is not very convenient and has the following disadvantages:

  • Multiple info-plists will be generated, which is not easy to manage
  • The configuration is messy

Mode 2. Multiple scheme-multiple Configurations

By default, a Scheme has two Configurations: Debug and Relesse. You can add a third one here

In this case, all configuration options become three, and you can create multiple schemes and select different Configurations for each Scheme

We then define a HOST_URL in user-defined and expose it in info-plist

By switching Scheme, you can switch the HOST_URL of different environments to achieve multi-environment configuration

In addition, you can configure different Appico for different schemes in User-defined

In this case, different targets have different ICONS. This method is more convenient than the first one, but it still needs to be configured in Builed Setting

Method 3. Xconfig files (this is how Cocoapods uses them)

First, create an xconfig file. Note that the xconfig file is named path-project-environment name when it is one-to-one with the environment

And select the corresponding Xconfig file in Configurations

Xconfig conflict handling

If you delete the HOST_URL and write the value of HOST_URL to different Xconfig files, you will get the same effect, but cocoa Pods have their own Xconfig files. Before doing this, you need to import the Xconfig file path of Cocoa Pods (note the root pods /) into the xconfig file to resolve the conflict.

In this case, HOST_URL in Debug mode is correctly displayed

When two Xconfig files have the same Builed setting configuration, this is also a conflict. When this happens, you need to inherit cocoapods with $(Inherited) in your own Xconfig file.

Summarize the above three ways:

  • Multiple targets, which control the code files and resource files that need to be compiled
  • Multiple schemes can provide multiple sets of environment variables
  • Multiple XConfig makes it easier to manage and configure these environment variables