skip to Main Content

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
}

2

Answers


  1. 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 {
    //        }
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search