Add multiple targets to swift project

Adding multiple targets to swift project is a need of hour. For example, if your app point to different end points. One end point is pointing to development server and second endpoint is for production or live server.

Why we need to add multiple targets in swift

  • If our app is using different servers end points
  • Single app is going to be used for different users(example customer user and admin user)
  • Need to made two app version (Free and Paid)

Steps to add multiple targets in swift

1. Create a duplicate target as shown in image

Create a duplicate target

2.Rename this duplicate target. We renamed it to Production. Same change name of info.plist file created by xcode for our production target.

Changing info.plist name for our new target

3.Mention same name in build setting of Production target.

Changing plist name in build setting of our new target

4. Add swift flag for our targets as shown in below image. Flags are required in order to place checks programmatically. Do these steps for all targets and just replace identifier. In this image we used “Dev”. For Production target we will use “Prod”.

Steps to add macro for target

5. Go to active schemes, next to play and stop button. Try to select a scheme and click on new scheme. A pop up will appear. Select Production target and name scheme as same name i.e. Production.

Adding new scheme for new target

Programmatically adding checks for different targets

Open ViewController.swift and add below code

      
        #if Dev
         print("We are using dev version")
        #else
         print("We are using production target")
        #endif

Here we use the flags set by us in build setting of the target. For default target we set flag as “-D Dev”. Thus here compiler will check for swift flags for targets. If you have more than two targets then you can as

        #if Dev
         print("We are using dev version")
        #elseif Staging
         print("We are using staging version")
        #else
         print("We are using production target")
        #endif

Where to go from here

In this post, we learned that how we can add multiple targets to swift project. By adding multiple targets developer cab be relieved from pain of commenting un-commenting codes related to different app versions.

%d bloggers like this: