Home > Net >  How to fix multiple targets condition in one place and access in all places?
How to fix multiple targets condition in one place and access in all places?

Time:04-02

In my Xcode, I have 3 Targets called target1, 2, 3.

I know to apply the condition for each Target.

#if Target1
#else Target2
#else Target3
#endif

But the above condition needs to apply the entire project in multiple places.

How to place this condition in one place and access it in the entire project?

Because if we made any changes we need to change in all places, so if we achieve above requirement if we change in one place that's enough.

I have implemented the below function but getting the error: Cannot find type 'File' in scope

//Single function in Utility class
    var getProjectName: String {
#if Target1
        return "Target1"
#elseif Target2
        return "Target2"
#elseif Target3
        return "Target3"
#else
        return ""
#endif
  
//Use case 1
switch BUtility().getProjectName {
case "Target1":
case "Target2":
case "Target3":
default:
    break
}

CodePudding user response:

You can place this class in target1 and get the rest of the bundleid's using the below BundleFinder class to get the bundle of the target.

class BundleFinder: NSObject {
    
    var targetName = Bundle.main.infoDictionary?["CFBundleName"] as? String
    
    private static var privateSharedInstance: BundleFinder?
    static var sharedInstance: BundleFinder {
        if privateSharedInstance == nil {
            privateSharedInstance = BundleFinder()
        }
        return privateSharedInstance ?? BundleFinder()
    }
    
    class func destroy() {
        privateSharedInstance = nil
    }
    
    override init (){
        super.init()
    }
    
    func getCurrentBundle() -> Bundle {
        if targetName == "target1"{
            return Bundle.main
        } else {
            return Bundle.init(identifier: "target2") ?? Bundle()
        }
    } }

And you can access like below:

     if BundleFinder.sharedInstance.targetName == "Target1"{
//
        }else {
//        }
}

CodePudding user response:

you can create a constants class and add the below

#if Target1
    static let MAIN_URL: String = "Target1"
#elseif Target2
    static let MAIN_URL: String = "Target2"
#else
    static let MAIN_URL: String = "Target3"
#endif

and you can use TARGET_NAME whenever you want in the project

  • Related