Search code examples
iosobjective-ccocoacompiler-directives

Using compiler directive to warn if a file is missing


I have a file that is included on the bundle that has the following name:

databaseX.sqlite

where X is the app's version. If the version is 2.8, the file should be named database2.8.sqlite. I have to be sure to include this file when the app is submitted to Apple.

Is it possible to create a compiler directive to check if the file is in the bundle?

I have tried this, without success

#define fileInBundle [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"LoteriaMac%@.sqlite", [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]]]

#if defined(fileInBundle)
#pragma message("file in bundle")
#else
#pragma message("file missing")
#endif

file in bundle is always shown even if the file is not in bundle.


Solution

  • This is not possible. You are trying to use a runtime check inside a compilation directive.

    In general, when compiling you cannot know whether there is a file in a bundle or not because the files are usually added to the bundle independently on code, after compiling.

    This is the same as checking whether there is a file present in the filesystem on another computer when compiling.

    To check that during build time, you can create a custom build script (Build Phases => + button) in your target, something similar to:

    APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"
    
    // there is probably some easier way to get the version than from the Info.plist
    INFO_FILE="${APP_PATH}/Info.plist"
    VERSION=`/usr/libexec/plistbuddy -c Print:CFBundleShortVersionString "${INFO_FILE}"`
    
    // the file we want to exist
    DB_FILE="${APP_PATH}/database${VERSION}.sqlite"
    
    // if the file does not exist
    if [ ! -f "${DB_FILE}" ]; then
       // emit an error 
       echo "error: File \"${DB_FILE}\" not found!" >&2;
       // and stop the build
       exit 1
    fi