0

I wanted to define few custom values in a pre-compiled header for different targets of my app. I tried the following to define headers, but none worked:

  1. by adding a header from Editor -> Add Build Setting -> Add User Defined setting and assign key value pair.
  2. Set Preprocess info.plist file to YES in Build Settings and set the header (.h) file in Info.plist Preprocessor Prefix file.

How do I add and set a pch key so that I can set true for UAT target and false for Production target using #if ?

Deepak Thakur
  • 3,453
  • 2
  • 37
  • 65

2 Answers2

1

If the sole purpose is to set different values for different environments - development, QA, UAT, Production, the xcconfig files can be used.

No conditional statements would be required but based on the configuration, it will take the appropriate values.

Steps involved would be:

  1. Add different Schema and different build Configurations.

  2. Add Configuration Settings file by selecting File->New->File and "Configuration Settings file" -> Development.xcconfig, UAT.xcconfig, Production.xcconfig etc

enter image description here

  1. Add custom keys of your choice in the config file and their relevant values in Key-Value pair as:

    endpointUrl = "Production_Url" for Production.xcconfig

    endpointUrl = "UAT_Url" for UAT.xcconfig

enter image description here

  1. Add relevant plist files and mention the keys from .xcconfig file to the .plist file. Create UAT.plist for UAT.xcconfig file and similar way for other supported configs.

enter image description here

  1. Set the appropriate plist path for each build configuration under Project -> Info -> Configurations

enter image description here

  1. Create a .swift file to read the config file such as:

public enum PlistKey { case EndpointURL

func value() -> String {
    switch self {
    case .EndpointURL:
        return "endpointUrl"
    }
} }

public struct Environment {

    fileprivate var infoDict: [String: Any]  {
        get {
            if let dict = Bundle.main.infoDictionary {
                return dict
            }else {
                fatalError("Plist file not found")
            }
        }
    }
    public func configuration(_ key: PlistKey) -> String {
        switch key {
        case .EndpointURL:
            return infoDict[PlistKey.EndpointURL.value()] as? String ?? "noValue"
        }
    }
}
  1. Call the url as:

let server_url = Environment().configuration(PlistKey.EndpointURL)

More detailed version at: https://www.freecodecamp.org/news/managing-different-environments-and-configurations-for-ios-projects-7970327dd9c9/

Alpana
  • 913
  • 1
  • 13
  • 22
0

If you are using swift. Then you can add custom swift flags. Under Build Settings -> Swift Compiler - Custom Flags.

and then in code use

#if YourFlag
....
#else
iamin
  • 66
  • 4