XCode – Add a file in project at build time

Imagine that you need to add a file in your XCode project the first time that you build the app.

For instance, you have a configuration file, in Swift, that you want to compile and embed in your app (instead of using a PLIST file that is in CLEAR…) during the build phase and of course use in your project.

How to do it?

Use the “Run script!” of XCode!

And add as code this:

source ~/.bash_profile
if ! [ -f "${PROJECT_DIR}/SecretKeys.swift" ]; then
  aws s3 cp s3://your-s3-bucket/mobile/theApp/SecretKeys.swift 

Let me to explain…

I want to use the bash and because I need to load my secret keys from my .bash_profile I need to tell XCode to reload my .bash_profile because XCode use its own shell.

Next, if the file is not already copied in my project, download from Amazon AWS S3 (or where you want) and copy to the project folder.

But is not enough! I want this file to be added automatically in XCode! Sure…

The trick is to create a new file with the same name of your remote file, like this:

And next, open it in the Finder and delete! Yes, delete, but from the Finder, not XCode.

In this way, we should see this file in red, Like an error.

Perfect! That’s all.

Now, if you build your project, the file from the cloud is downloaded and saved in the project folder, exactly in the ${PROJECT_DIR}.

After the build, your file became visible and is no more RED.

You can use all this file contents in your project.

All of this complications is due to the compilation of the Swift file and not to the PLIST files.

Best way to embed in your app something secret is to compile a file or something else of course, but not a PLIST. IMHO.




Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.