iOS XCode: How to load a value from a user-defined setting from build settings at run time

1.5k Views Asked by At

I've got the following constant in the code:

static NSString* const MyUrl = @"www.myurl.com";

Is it possible at all to create a user-defined setting and assign a value which can replace the value of MyUrl const at run time or during archive?

My situation is the following: I have a project with various targets. Each target points to a different URL in the code. It would be great if I could manage the URL through a user-defined setting rather than having to change the code every time I change the target.

4

There are 4 best solutions below

0
Arik Segal On BEST ANSWER

Consider using info.plist for storing such values.

2
Jatin Chauhan On

No you could not change the value of const variable.

You can change the value of URL string by simply NSString *myURL = @"www.url.com";

and use the global variable in AppDelegate and use that from any where in project.

2
icould On

I think you need to use a database or any other source out of your app. And fetch the URL string whenever it changes and you can use your NSString variable inside the code. You can use parse for your need (However, Parse will stop their service next year but there are lots of free online DBs you can use). With this method you don't need to change your code to update URL strings. I hope I could get what you need correctly.

0
Shripada On

You can use pre processor macros for this purpose. Goto to Xcode>Project>Target>Build Settings>Preprocessor Macros. Then for every build configuration (Debug, release, etc) add a target specific macro. In your source code, you can now identify your target, by just referring to the macro using #ifdef.

Example:

#ifdef TARGET1
static NSString* const MyUrl = @"www.myurl.com";
#endif

#ifdef TARGET2
static NSString* const MyUrl = @"www.myur2.com";
#endif

The following image depicts the declaration of TARGET macro in build settings-

enter image description here