How do I get the name of the target that is curren

2020-04-03 09:28发布

问题:

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.

回答1:

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


回答2:

Swift 3.0 Solution.

func getTargetName() -> String {
    return Bundle.main.infoDictionary?["CFBundleName"] as! String
}


回答3:

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"]



回答4:

On Swift 4.0

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


标签: ios xcode build