15

I have an Xcode project with several targets. Let's say the target names are AppFreeVersion and AppPaidVersion. They share the same codebase, but I want to implement some logic that is only for one of the targets.

Without modifying my scheme or build settings, is there a way to get the string of my current target name? The solution given in this question requires me to pass an environment variable in the build setting, which I don't want to do.

Community
  • 1
  • 1
Enrico Susatyo
  • 19,372
  • 18
  • 95
  • 156
  • Maybe the following post can help [Answer](https://stackoverflow.com/questions/18783055/how-to-get-target-name/52966225#52966225) – Reimond Hill Oct 24 '18 at 11:07
  • Maybe the following question can help [Answer](https://stackoverflow.com/questions/18783055/how-to-get-target-name/52966225#52966225) – Reimond Hill Oct 24 '18 at 11:08

6 Answers6

10

How about adding ${TARGET_NAME} in your info.plist?

And I guess you already know how to get it

Obj-C

[[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];

Swift

let targetName = NSBundle.mainBundle().infoDictionary?[key_name] as String
Niko Adrianus Yuwono
  • 11,012
  • 8
  • 42
  • 64
8

Swift 3.0 Solution.

func getTargetName() -> String {
    return Bundle.main.infoDictionary?["CFBundleName"] as! String
}
Atef
  • 2,872
  • 1
  • 36
  • 32
0

The accepted answer by Niko is still working for me on Xcode 12.2 and iOS 14.2

Here is a screenshot to better clarify what needs to be done in Info.plist:

Info.plist screenshot

You need to do this for each target's corresponding Info.plist

You don't even need to use $(TARGET_NAME) as the value, you can give your own custom unique values and check for those instead.

banana1
  • 545
  • 1
  • 4
  • 16
0

First you have to add the target name property in the .plist file of respective target. then you can get it anywhere in the code.

print("Target Name = " + (Bundle.main.infoDictionary?["TARGET_NAME"] as! String))

enter image description here

-1

Just set Target name in your Scheme -> Environment Variables -> add Name and Value. eg: targetName = "mytesttarget"

Obj-c

NSDictionary* envir = [[NSProcessInfo processInfo] environment];

NSString* targetName = envir[@"targetName"];

Swift

let envir = NSProcessInfo.processInfo().environment

let targetName = envir["targetName"]

SaRaVaNaN DM
  • 4,390
  • 4
  • 22
  • 30
-2

On Swift 4.0

let targetName = Bundle.main.infoDictionary?["TargetName"] as! String
juanram0n
  • 356
  • 3
  • 22
  • this is not working, the app gets crashed. it did not found the "TargetName" key in "Bundle.main.infoDictionary". – Umair Ali May 15 '20 at 17:49