Custom build scripts – including static files

I’ve spent a while trying to work out the best way to conditionally include a static file into an xcode project at build time. It appears that there’s not a very elegant way of doing it!

My use case is to switch a static json file based upon the build configuration. We already do this for the bundle identifier and app icon and this is relatively easy as the references to these files/values are processed at build time are pre-processed. Using preprocessor variables allows you to switch these values at build time giving you conditional configuration.

For static files, like json, that do not get processed until runtime you can not use this approach.

The best solution I have found for this approach is to switch the whole file using “Run Script” under “Build Phases”. We add the two versions of the files we want to switch between but do not add them to any targets. You can check this by selecting the files in xcode and under “File Inspector” untick the “Target Memberships” next to each target.

We then add the script:

echo "Checking configuration to determine whether running Production Build: CONFIGURATION=$CONFIGURATION"
if [ "$CONFIGURATION" == "PROD" ]; then echo "Copying ${SRCROOT}/${PRODUCT_NAME}/ADMS_AppLibrary/prod/ADBMobileConfig.json directory to ${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app"
cp -R ${SRCROOT}/${PRODUCT_NAME}/ADMS_AppLibrary/prod/ADBMobileConfig.json ${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/ADMS_AppLibrary/ADBMobileConfig.json
echo "prod/ADBMobileConfig.json has been copied."
else
echo "Copying ${SRCROOT}/${PRODUCT_NAME}/ADMS_AppLibrary/dev/ADBMobileConfig.json directory to ${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app"
cp -R ${SRCROOT}/${PRODUCT_NAME}/ADMS_AppLibrary/dev/ADBMobileConfig.json ${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/ADMS_AppLibrary/ADBMobileConfig.json
echo "dev/ADBMobileConfig.json has been copied."
fi

This contains a lot of writing items to the log which you don’t really need but it does make debugging easier and means very quickly you can check what is happening.

We have hit a couple of gotchas using this approach. Firstly make sure your paths match, not all of your files will be under the folder marked “${PRODUCT_NAME}”. Secondly if your paths contain spaces then the copy command will fall over, just wrap the path in speech marks if this is the case.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>