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, then most common approach for a beginner iOS developer is to comment out different end points while generating builds for specific environment. Creating individual targets for different configurations saves iOS developers from this headache of commenting and uncommenting code for different configurations/settings.
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
2.Rename this duplicate target. We renamed it to Production. Same change name of info.plist file created by xcode for our production target.
3.Mention same name in build setting of Production 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”.
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.
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 uncommenting codes related to different app versions.