Best way to organize API base URL for different environment in Xcode

▼魔方 西西 提交于 2019-12-11 08:40:53

问题


We have 3 environments Dev, Stage and Prod for our API. I have 3 targets and schemes for 3 environments setup in my Xcode which have different builds, code signing, profiles and plist.

How do I do the same for API base URL? right now I have all in 1 prefix file. Because it is 1 project so all 3 targets are using the same file and I have to change the comment out every time I build for different environment.

//DEV
#define SERVER_URL @"http://api.dev.com/api/"
//STAGE
#define SERVER_URL @"http://api.stage.com/api/"
//PROD
#define SERVER_URL @"http://api.prd.com/api/"

What is the best way to organize API base URL for different target environment in Xcode?

Thanks,


回答1:


First, for anything as complicated as this, I strongly recommend using xcconfig files rather than the build pane for configuration. This article is fairly dated, but the information is still fairly accurate (minus some minor changes in the Xcode UI).

Using that technique, you can mix-in different xcconfig files for different build configurations (Dev, Stage, Prod). Within the correct xcconfig, you can use GCC_PREPROCESSOR_DEFINITIONS to set any macros you need:

GCC_PREPROCESSOR_DEFINITIONS = SERVER_URL=@"http://api.dev.com/api/"



回答2:


I played around and found a simple yet effective solution for me.

I put the API base URL as a value in the plist of each target with the key @"ServerURL". Then on the singleton class interfacing with the API, I put this in the init

NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
serverURL = [infoDictionary objectForKey:@"ServerURL"];

There I have the correct serverURL based on which target I'm building.




回答3:


For each of your targets, you could add a different preprocessor macro (located in the build settings of your targets). E.g. your Dev target defines DEV=1.

The DEBUG macro is one good example and should be existent for your debug configuration in each target. You have to specify your custom preprocessor macros for each configuration (Debug, Release, ...)

In your prefix header file you can now check with #ifdef or #if defined, which target you are currently building.

#if defined DEV
  #define SERVER_URL @"http://api.dev.com/api/"
#elif defined STAGE
  #define SERVER_URL @"http://api.stage.com/api/"
#elif defined PROD
  #define SERVER_URL @"http://api.prd.com/api/"
#endif

I think it should work like this but don't pin me down on this.



来源:https://stackoverflow.com/questions/25571641/best-way-to-organize-api-base-url-for-different-environment-in-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!