How to get Target name?

随声附和 提交于 2019-11-27 15:26:21

You can add "TargetName" key to your Info.plist file:

Then you can access it (swift code):

var plistFileName = NSBundle.mainBundle().infoDictionary?["TargetName"] as String
NSLog(@"Target name: %@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]);

Hope to help you!

Edited: "CFBundleName" thanks Max and Daniel Bo for your commend

Swift 4, Xcode 9+

Bundle name:

Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? ""

Bundle display name:

Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? ""

Swift 3, Xcode 8+

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

In Xcode 7.3.1

if let targetName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String{
    print(targetName)
}

** For Swift 4 **

I am not sure how good it is to have a Constants file in Swift but you could create something like that:

enum TargetType:String, CaseIterable{
    case target1 = "My Target 1"
    case target 2 = "My Target 2"
    case unknown
}

var currentTarget:TargetType = {
    return TargetType(rawValue: (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "")) ?? .unknown
}()

So you can called it any time like that

if currentTarget != .unknown{
    print(currentTarget.rawValue)
}

If you want to add the variable inside a Constants class then:

class Constants: NSObject {

    static var currentTarget:TargetType = {
        return TargetType(rawValue: (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "")) ?? .unknown
    }()

}

I must credit the original answer by vk.edward.li, as this answer only merely expands on it.

All the build setting macros can easily be used in source code as preprocessor macros too. The problem is that they're not set in advance; you have to specify which ones you get access to, yourself.

I've already added three extra preprocessor macros. Simply click the +, and add this: TARGET_NAME=\""$TARGET_NAME"\", and you've granted yourself access to one more build setting macro.

Project settings ––> Build Settings ––> Apple Clang - Preprocessing[Preprocessor Macros]. Note that if you try to insert them for both compilation modes at once, the DEBUG=1 macro will get deleted, but it can as easily be added right back afterwards.

It's also worth noting that the macro values should be set differently for different languages: Objective-C and C++/Swift, etc. This is due to the NSString prefix used in Objective-C, so for that language, it should be MACRO=@\""$MACRO"\" instead of MACRO=\""$MACRO"\".

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