kalyan ganta
kalyan ganta

Reputation: 74

Write an if condition for specific target in the app

I'm trying to write an if condition in appdelegate method, There are two targets in my app. The if condition should work only for one target.

#if TEST
    var startUrl: String = "http://www.example.com"
#elseif TEST_2
    var startUrl: String = "http://www.example2.com"
#endif

TEST and TEST_2 are two targets, and URL will be selected according to the selected target. This is the start url of my app. There is a function after this. I need that function to be executed only if TEST target is running. What do I do?

Upvotes: 5

Views: 6396

Answers (3)

Alain T.
Alain T.

Reputation: 42133

You could create two small source files with a different "constant" declaration in each one. Then include the appropriate source file only in the target it pertains to.

for example

 // file: example1.swift (only included in target 1)
 let targetStartURL = "http://www.example1.com"

...

 // file: example2.swift (only included in target 2)
 let targetStartURL = "http://www.example2.com"

The you won't even need an if statement in your delegate. You simply use the global variable in the initialization:

 var startURL = targetStartURL

Upvotes: 1

marshallino16
marshallino16

Reputation: 2671

Testing your target name is not good. Especially if this code goes to production.

Let's assume:

TEST is a target pointing your Stagging Env (integration) And TEST_2 is a target pointing your Production Env.

A better approch would be :

  • Open the Preview's target's build settings
  • Create a Preprocessor Macro like STAGGING=1 for your target TEST

Then, all you have to do is:

#if STAGGING
    var startUrl: String = "http://www.example.com"
#els
    var startUrl: String = "http://www.example2.com"
#endif

Upvotes: 6

Vini App
Vini App

Reputation: 7485

You can get target name like this :

let targetName = Bundle.main.infoDictionary?["CFBundleName"] as! String

Upvotes: 1

Related Questions