robhasacamera
robhasacamera

Reputation: 3326

Xcode build for environment

Currently working on an iPhone app that connects to several different webservices. These webservices have several different addresses depending on the environment we're connecting to:

I'd like to know what the best convention is for defining these urls and switching between them depending on what environment we want to build for. Is this something I can define in my build settings or can I set up various builds using a define to specify the environment?

Note: Not sure if it matters but for the moment we're using purely Objective-c although we may integrate Swift sometime much later in the project's lifetime.

Upvotes: 0

Views: 147

Answers (2)

quellish
quellish

Reputation: 21244

Use NSUserDefaults.

For example, set the production value as the fail over default by passing it in a dictionary to -registerDefaults:. This puts the value in the NSRegistrationDomain. Then for your validation and testing you could:

  • Set the value in the NSArgumentDomain using code. This would override the value in the NSRegistrationDomain.
  • Pass the value as a launch argument. When you do this, the value is inserted into the NSArgumentDomain, again overriding any value in the NSRegistrationDomain.

NSUserDefaults searches the domains in a specific order to find a value. This behavior is explained well in this post by oleb.

This approach is flexible, and does not have some of the disadvantages of using conditional compilation to solve this problem.

Upvotes: 0

weso
weso

Reputation: 219

This work for me:

#ifdef TARGET_PROD
    #define BASE_URL @" http://www.example.com/api/"
#endif
#ifdef TARGET_VAL
    #define BASE_URL @"http://staging.example.com/api/"
#endif

#ifdef TARGET_TEST
    #define BASE_URL @"http://staging.example.com/api/testing/"
#endif

Put this, for example, in Commons.h or a common project file.

And for any Target go to Build Settings and set Processor Macros adding TARGET_PROD in "Debug" and "Release", TARGET_TEST for target test and TARGET_VAL for target staging. When you make a request simply append at your BASE_URL the SERVICENAME like this:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@,%@", BASE_URL,yourService]]];

Upvotes: 1

Related Questions