Swift get `Scheme Name or Swift Compiler - Custome Flags` value at Run Time

Viewed 3868

I have xcode project in swift with 3 schemes.

I have plist files for each of that schemes, in that plist file i have constants values like fontname, color and logo name, etc. Supose i have 3 schemes 1. Banana 2. Orange 3. Apple

So i for these all scheme i have plist file names as 1. BananaScheme 2. OrangeScheme 3. AppleScheme

Now i have one swift file called as SchemeConfig in this file i have to read this plist file and returns constant's value.

To read plist file i have one method as below

private func getConfigFile() -> [String: Any]? {
        var configFileName: String = ""
        #if Banana
            configFileName = "BananaScheme"
        #elseif Orange
            configFileName = "OrangeScheme"
        #elseif Apple
            configFileName = "AppleScheme"
        #endif

//        let targetName = Bundle.main.infoDictionary?["TargetName"] as! String
        if let url = Bundle.main.url(forResource: "\(configFileName)", withExtension: "plist"),
            let dict = NSDictionary(contentsOf: url) as? [String:Any] {
            return dict
        }
        return nil
    }

It's working perfectly, but the problem is i don't want to check that #if condition Can i get that Swift Compiler - Custome Flags value at run time?

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

What exaclty i want is remove #if condition to check scheme.

private func getConfigFile() -> [String: Any]? {
    var configFileName: String = ""

    let schemename = //Code to get scheme name
    if let url = Bundle.main.url(forResource: "\(schemename)Scheme", withExtension: "plist"),
        let dict = NSDictionary(contentsOf: url) as? [String:Any] {
        return dict
    }
    return nil
}
1 Answers

So you can create a user defined variable based on the Compiler flag.

First create a user defined variable in build settings. In this case CURRENT_SCHEME_NAMEenter image description here

Then give each compiler flag a different value like this:

enter image description here

Next you want to add this key value pair to your info.plist:

enter image description here

Finally you can access this value at run time using:

let schemeName = Bundle.main.infoDictionary!["CURRENT_SCHEME_NAME"] as! String

Related