MAS Preparation, Part 5

Mac App Store receipt validation

In the last installment of Preparing for Mac App Store Submission, I discussed the (general) source code modifications that you may need to make in order to convert your downloadable Mac OS X project into one acceptable for the Mac App Store (MAS).

Now, in this fifth part, I will talk about a more specific addition to your source code, functionality for checking the presence and validity of a MAS receipt file.  While this change is not required, and would not cause your submission to be rejected, it is strongly recommend for reasons detailed below.  In fact, we will start there…

0. Consider the reason for receipt validation

Before implementation, it is good to understand, in general terms, the purpose of receipt validation.

When somebody “purchases” an application from the Mac App Store, a receipt file is added to the downloaded bundle authenticating it; this includes free products as well.  However, the level of checking provided by the system itself is minimal.  Soon after the MAS launch, it was discovered that there was a fairly simply method [details deliberately omitted] by which even a simple-minded software thief could circumvent the very basic protections and run stolen MAS applications.

The solution, of course, is to verify the validity of the software receipt for your application, which helps prevent “script kiddies” from easily stealing and distributing your products.  Of course, it is never quite as simple as that, especially since code signatures and encryption are inherently complex, and the program needs to validate a receipt file that has not been created yet (making this code rather tricky to test).

Keep in mind that this validation process is optional, so you can choose not to do it all, to fully validate the receipt file, or to implement only partial checks; the choice is up to you.

The official Apple documentation for this process is in Validating Mac App Store Receipts.

1. Obtain a sample receipt for testing

As mentioned above, your first challenge is that the receipt checking code needs to be able to validate a receipt file from a purchase that is to be made in the future.  To do this, you may want to get a sample receipt for testing.

This used to be fairly easy, as Apple provided a sample receipt, along with the associated validation data, to Mac developers.  Unfortunately, recently (as in, since this series began), the certification signature on the original sample receipt expired and, instead of providing a newer one, Apple has decided to remove the sample receipt entirely in favor of connecting to the iTunes servers to obtain one directly.  Whatever.

Now, the process involves getting the application to initially quit with an exit code of 173, which indicates a failed verification, which is supposed to trigger iTunes to prompt you for your (test) account credentials and then download a valid receipt and insert it into the application bundle, as described in Test During the Development Process.  In practice, this definitively does not work all of the time during development, and the prerequisites are not clear.

What is clear is that the application needs to be signed before Mac OS X (version 10.6.6 or higher) will request iTunes credentials, and that they need to be for a test account.  However, any old test account will apparently not do, and a failure to produce and/or download a receipt displays no error message (just no receipt and only a vague “returnCode:1” in the console).  It appears to be that the application needs to already be in iTunes Connect and that the test account must be associated with that application via the master company account.  Unfortunately, for the moment, this remains as an exercise for the reader.

Another (unproven) approach could be simply borrowing a receipt from any purchased application from the Mac App Store.  You will need to know the exact bundle identifier (fairly easy), version number (also easy), and computer GUID (not quite as easy), but you could use such a receipt exactly like the sample receipt previously provided by Apple.

Important: Do NOT include any receipt files in your project.  Receipts are specific to the application, version, and system, and they are generated and added by the Mac App Store/iTunes; including a receipt in your submission bundle will result in summary rejection of the application.

2. Locate the receipt file

The first step to take in your source code is to locate the receipt file for checking.  In the release version, intended for distribution, the location of the receipt is always within your application bundle at ‘Contents/_MASReceipt/receipt‘.

If you decide to use a sample receipt for testing, you will probably want to define its (different) location, the parameters expected from the sample receipt, and a definition to use for conditional compilation.  In our case, the debug versions define USE_SAMPLE_RECEIPT and the other values (from the old sample receipt) like so:

#ifdef APPSTORE
    #define RECEIPT         "Contents/_MASReceipt/receipt"

    #ifdef _DEBUG
        #define USE_SAMPLE_RECEIPT
    #endif

    #ifdef USE_SAMPLE_RECEIPT
        #define SAMPLE_RECEIPT  "/Users/Gregg/Desktop/receipt"
        #define SAMPLE_BUNDLE   "com.example.SampleApp"
        #define SAMPLE_VERSION  "1.0.2"
        #define SAMPLE_GUID     { 0x00, 0x17, 0xF2, 0xC4, 0xBC, 0xC0 }
    #endif
#endif

Note that we explicitly define different path variables (RECEIPT versus SAMPLE_RECEIPT) and only define the sample parameters when USE_SAMPLE_RECEIPT is defined.  This is additional protection against accidentally using a property intended only for testing in release code.  For the same reasons, we also include this check in the code before the main loop:

#ifndef _DEBUG
#ifdef USE_SAMPLE_RECEIPT
    ErrorMessage ( "Warning!  Sample receipt is being checked in release version." );
#endif
#endif

So, our first verification function is GetReceipt(), which returns the path of the (untouched) receipt file.  The routine obtains the path to the bundle and then generates the path directly to the receipt for later verification, adjusted appropriately if USE_SAMPLE_RECEIPT is defined.  Additionally, just for another sanity check, it also verifies that the actual bundle identifier and short version string match definitions within the code (so we can safely use the definitions later).

3. Check the signature

The next step in validating a receipt is to check the signature to verify that it is properly signed by Apple.  Sample code for doing this (as well as the next two steps) can be found in the Implementation Tips section of the Validating Mac App Store Receipts document, as well as via a nice web search.

Our second verification function is CheckSignature(), which returns a PKCS7* data pointer (and is essentially a fleshed out version of Listing 1-4 in the section linked above).  It opens the receipt file, validates the data types, adds the “Apple Root CA” certificate, and verifies the receipt signature (via PKCS7_verify), then cleans up everything except the receipt pointer, which is returned for use in the next function.

At this point, you know that the receipt file exists, it contains data, and its signature is valid.

4. Verify the receipt contents

The next step is validating a receipt is to verify the receipt contents and confirm that the receipt is intended for your application and the current version number.  The document referenced above gives more details about implementation, but the process is essentially stepping through the objects in the receipt and processing each one appropriately.

There are four types of objects within each receipt that are relevant to the validation process: bundle identifier, bundle version, opaque value, and hash.  In this step, you want to verify that the bundle identifier and bundle version match the hard-coded definitions for your project.  Note that matching against values retrieved from the bundle is not as safe, since the ‘Info.plist’ file could potentially be modified to match an invalid receipt.  Also, you will want to store the bundle identifier, opaque value, and hash object values for checking during the next step.

Our third verification function is VerifyData(), which accepts the PKCS7* data pointer returned by the previous function.  It loops through the objects in the receipt and processes them appropriately, failing if either bundle identifier or bundle version do not match our hard-coded values (IDENTIFIER and VERSION, or SAMPLE_BUNDLE/SAMPLE_VERSION), or if either of these objects is missing from the receipt.  Additionally, it saves the objects necessary for the next step.

At this point, you know that the receipt is intended specifically for the current version of your application.

5. Verify the system hash

The next (and, perhaps, final) step in validating a receipt is to verify the system hash to confirm that the receipt is intended for the particular system on which it is being launched.  This step prevents the outright copying of entire application bundles from one system to another.  Of course, on failure, users are presented with the opportunity to enter their iTunes account information to obtain a valid receipt automatically, so legitimate customers are protected.

The general process for this step involves two parts: obtaining the computer’s GUID and then computing the hash of the GUID, which is then compared to the hash value stored in the last step.  The sample code in the Apple documentation referenced above describes both steps sufficiently (in listings 1-3 and 1-7, respectively).

Our fourth verification function is VerifySystem(), which calls a CopyMacAddress() function to perform the first part of the process, then uses that information to check the system hash.  More specifically, the GUID returned is added to a digest, along with the opaque value and the bundle identifier, and an expected hash is calculated.  The routine verifies that the computed hash length is the same as that of hash and then checks that the contents are identical.

At this point in the process, you now know (to a reasonable degree) that the receipt file exists and is completely valid for that system running the current version of your application.

6. Take extra validation steps

If you are particularly concerned (or paranoid), you can take extra validation steps, such as verifying the certification authorities, double-checking the bundle signature, or (apparently) even sending a receipt back to the App Store for verification.  You can also take steps to obfuscate your code and make it harder for crackers to find and modify the application to circumvent your checks, and Apple provides some suggestions.

However, just taking the general steps documented here will probably eliminate 99% of the problem, and with robust coding, error checking, and testing, theft of the Mac App Store version of your game should be minimal.  (In fact, you will likely lose significantly more money to downward pricing pressures than to piracy, but that is another topic altogether…)

Conclusion

With the addition of receipt validation checking to your project source code, your application should not be subject to simple receipt spoofing, once accepted into the Mac App Store.  In the next (final) installment, Part 6: App Sandboxing implementation, I will discuss the process of preparing for and implementing application sandboxing, as required for the Mac App Store by June 1, 2012 (recently pushed back from March 1st).

MAS Preparation, Part 4

Source code modifications

In the previous installment of Preparing for Mac App Store Submission, I provided some guidelines for application data and resources that should be followed (where applicable) as you transform an existing Mac OS X game project into a project that can be successfully submitted to the Mac App Store (MAS).

In this fourth part, I will describe a number of modifications to the source code of your project that you may want to make to avoid unnecessary MAS rejections and, perhaps, improve your customer support and project maintenance.  These recommendations build on the theme of earlier posts, as most of these changes are due to Apple restrictions against anything having to do with downloading or external sales, including the use of registration codes.

As before, these suggestions are based solely on our experience with our products, so it could help to understand the basics of our sales system.  We have two separate downloadable builds for each Mac OS X product: one is a trial version, with limitations, and the other is a full version, which is unrestricted but requires a customer-specific registration code (as well as the hidden download location).  In order to better understand our customers, each web link in the program adds a very basic tracking code, so we know which version is being used; when online high scores are submitted, we include a hash of the registration code so the scores can be applied to the correct player account.

For this process, we have created a new store version, which is unrestricted (like the full version), includes available extra data (avoiding downloads), and cannot require a registration code.  (Instead, the Mac App Store automatically includes a “receipt” which should be checked, as discussed in the next installment.)  Here are the steps we took…

1. Store game data within user library folder

For the Mac App Store, game data that is not directly created by the user must be stored within the user library (not documents) folder.  Originally, we stored our saved games and statistics in ‘~/Documents/<project name>/<player>’, which made them easily accessible for our customers, but MAS guidelines (and an explicit rejection) required us to relocate such files to ‘~/Library/<project name>/<player>’, where they are less discoverable by users, especially since ‘~/Library’ is now hidden in Finder.  In our case, we actually relocated the files for all SKUs, including a function in the downloadable versions to automatically copy this game data to the new location, to make future customer support more manageable.

Note that, with application sandboxing (as discussed in the final installment), the actual location of the (sandboxed) user library is a significantly longer path name, and the main user documents folder is not accessible by default.  Obviously, the paths given above are illustrative only; one should never hard-code a path in project source code.

2. Remove all registration code via conditionals

Since any sort of registration code is forbidden, you should remove all registration code functionality via conditional compilation.  As part of our Project modifications earlier, we added an APPSTORE preprocessor variable to the store version target (only), which now allows us to remove sections of code with “#ifndef APPSTORE”/”#endif” sections.

In our case, every place in the code where the trial and full versions were different were already denoted with the preprocessor variable ‘DEMO’, so we only needed to look at each such section and decide if it should be like the full version (i.e., no limitations), which was the case most of the time, or like the trial version (i.e., no registration codes).

3. Add fixed internal MAS registration code

Because we used registration codes to differentiate between customers, we needed to add a fixed internal MAS registration code for all store version customers.  In order to replicate the previous functionality for online high score submissions, we needed a way to distinguish among different users without accessing any individually identifiable user information.  Alas, in the end, we had to provide a hash of some system information that was reasonably unique, and simply accept the possibility of a certain number of collisions.  (Thus far, MAS sales have not been high enough to get to levels where collisions are likely, though.)

Honestly, there is a possibility that information from the included MAS receipt could have provided a better (unique) customer identifier, but our implementation (above) was completed before receipt checking was considered.  In this case, that is left as an exercise for the reader (but comments on implementation are encouraged).

4. Update version tracking codes

For the store version, you should update any version tracking codes in your project, using conditional compilation (APPSTORE) where necessary.  This will allow any usage statistics to differentiate between downloadable and MAS customers, as well as from trial version users (i.e., potential customers).

In our case, we simply add a character to the end of link URLs (i.e., as part of a single GET variable) that makes this distinction, so we just added another legal value for MAS purchases.  Additionally, our shortened version numbers are slightly different so (savvy) players can identify the product played on the online high score pages (for example, on this FreeCell scores page, see the ‘Product’ column).

5. Remove or modify marketing screens

Consider whether you should modify or remove any marketing screens in your product.  If you have dialog boxes which have the occasional link to ordering pages or downloadable content, you will need to remove those links (and any referencing text); if you have dialogs that are explicitly for the purpose of marketing, it may make sense to remove them entirely instead.

In the case of our products, we include a fairly self-explanatory ‘Help Center‘ screen which not only contains links to the help files for the product, but also serves as a portal to all manner of support services, including sales (verboten), registration code entry (not allowed), customer support email (probably OK), and suggestions for other games (who knows?).  We found that removing the disallowed and questionable content from these pages made them almost pointless, so we instead replaced the entire dialog with a direct link to the help file contents page (within the bundle).

6. Remove links to any downloadable content

You must remove any links to downloadable content or risk the rejection of your product.  Note that these links (and, in truth, a number of other “offenses”) may not always be obvious on initial review, so your product can certainly get accepted once and then later rejected for something that was there in the first version; it has happened to us more than once.  (All Apple reviewers are not created equal.)

In the case of Pretty Good Solitaire, we have card sets which customers can freely download, plus a feature to check for and download updates, both of which are forbidden in the Mac App Store.  The following subsections describe the issues that we had to address to prevent suggesting that there was anything outside the MAS playground.

6a. Remove download links from main menus

We had to remove our ‘Download Additional Card Sets‘ menu option from both the main and game menus.

6b. Remove version checking from main menus

We had to remove our ‘Download Latest Version‘ menu option, which includes an implicit version check, from the both the main and game menus.

6c. Remove download links from submenus

We had to also remove a ‘Download Additional Card Sets‘ menu option from our submenu that players use to select the desired card set (a logical and convenient place to find it).

6d. Remove download links from buttons

Finally, we had a ‘Download Additional Card Sets‘ button within the program preferences, which also had to be removed (actually, hidden).

Note:  In all of these cases, rather than modify our user interface (.nib) files, and thus have to manage different sets of files, we added conditional code that simply removed the offending menu option or hid the button, keeping the source code (including .nib files) identical between downloadable and store versions (distinguished solely by the presence/absence of APPSTORE).

7. Review any use of the Application Support folder

Before submitting your application to MAS, carefully review your use of the Application Support folder (if any).  Specifically, you are allowed to create and (appropriately) use a folder at ‘~/Library/Application Support/<app-identifier>’, where <app-identifier> “can be your application’s bundle identifier, its name, or your company’s name.”

However, there is a twist:  “These strings must match what you provided through iTunes Connect for this application.”  This particular requirement is somewhat buried in the guidelines, and it is not always checked.

In our case, we inadvertently created but did not use (in the store version) a folder, ‘~/Library/Application Support/Goodsol’, which seems to fit the criteria.  However, it was supposed to end in ‘Goodsol Development’ to meet the letter of this requirement.  This “violation” was not discovered until our third or fourth submission, and our downloadable versions already used the folder extensively as named.  Fortunately, the store version did not actually use it (by virtue of including all downloadable content), so we just removed the spurious creation of an empty folder.  Problem solved (albeit with yet another rejection and delay).

Conclusion

With the above modifications to source code, plus perhaps a little detective work finding similar issues with any particular application, your project should be tentatively ready for submission to the Mac App Store.  In the next installment, Part 5: Mac App Store receipt validation, I will discuss the reasons that you should probably validate receipts in your shipping product and provide a few links to useful code and resources.

MAS Preparation, Part 3

Data and Resource guidelines

In the previous installment of Preparing for Mac App Store Submission, I detailed changes to the information property list that are necessary (or recommended) for a Mac OS X game project being converted to one suitable for MAS submission.

This third part deals with practical implications of guidelines for project data and resources, in particular, artwork and help files.  These points are necessarily somewhat specific to the manner in which we implemented our products, but they should give you some idea of items to look out for, and as always, comments on your experiences are encouraged.

Now, please review all of the artwork and other (non-code) resources in your project with these points in mind…

1. Include a 512×512 image in the application icon

The Mac App Store requires a 512×512 image in the application icon file.  Although this is generally overkill for an application, it is necessary for MAS submissions, where that image size is (presumably) used for presenting your product to users.

We actually produce our Macintosh (.icns) icons under Windows using Axialis IconWorkshop, which handles the required sizes without problem; we recommend this tool for processing icons for multiple platforms.  (We have no affiliation with Axialis, except as a satisfied customer.)

2. Update branding artwork

Although it seems (and truly is) silly, you need to review your branding artwork and update anything that even hints that there is another way to obtain software than through the Mac App Store.

Herein lies a theme: Apple hates downloads; Apple hates external sales.  Any suggestion that a customer may download or purchase anything outside of MAS will result in the rejection of your submission.  (Trust me, we had this thrown in our face, via rejection, more than once.)

In our case, we had a static bitmap used as a splash screen.  It included the (innocuous) line, “Download the latest version of Pretty Good Solitaire from http://goodsol.com“; it was hardly noticeable, and the web address was not even a hot link.  Rejection.  We had to remove that text before resubmitting (and we also removed the line with our support email address, just in case).

3. Add any extra product data desired

Continuing with the theme, you will need to add any extra product data that you may want customers to have, especially any data previously available via download.  In our case, we have (20) extra card sets that are available for Pretty Good Solitaire customers to download (and, likewise, extra tile sets and custom layouts for Pretty Good MahJongg), so these needed to be added to the main bundle to avoid Apple’s allergy to downloading.

The one minor advantage of this, of course, is that Apple has to bear the full download bandwidth burden.  (Card set artwork is not small.)

4. Remove trial version resources from the project

If appropriate, remove any resources used only in trial versions of your product.  In our case, we have an exit screen for trial users, as well as a separate interface (nib) file with all dialogs displayed (only) in the trial version, so we removed these.  (There is no sense including unused files, especially if they could give Apple more places to find reasons to reject.)

Similarly, if you have an install bitmap in your bundle, as I recommended in Making Mac Disk Images Pretty, you may as well remove that, too (since there is no disk image packaging to be done).

5. Remove any ‘How to Order’ section from help files

Review your help files and remove any pages that discuss verboten topics, such as downloading, registering, or (especially) purchasing the product.  We have an entire section called “How to Order”, dealing with all of those topics, that is just removed wholesale for the MAS submission (but remains in our downloadable versions); it was the cause for a rejection.

Note that Apple does not reject for simple web links back to a product site, which itself may have loads of sales and download information, but you will want to be careful about the surrounding text.

6. Remove text referring to downloading or sales

Building from the previous guideline, after removing entire pages about problematic topics, check other help topics and remove any text referring to downloads or sales, even indirectly.

In our case, we have rule pages for our bonus games, which are provided in the full (purchased) version, and we removed the line, “Note: This game is only available in the full version of Pretty Good Solitaire.”  Elsewhere, we also replaced “the full version” with “this version”.

Conclusion

Using the above guidelines, you should be able to make sure that your project does not include any content that Apple may find “objectionable”, giving them cause to reject the submission.  In the next installment, Part 4: Source code modifications, I will discuss the numerous (small) changes that may be necessary in your project source code.

MAS Preparation, Part 2

Property List (Info.plist) changes

In the last installment of Preparing for Mac App Store Submission, I discussed the project modifications that are necessary (or recommended) for converting an existing Mac OS X project to one suitable for MAS submission.

This second part describes the changes to the information property list for your application that you should make for successful submission and to eschew rejections for simple issues.  As before, comments about any other issues or different experiences are certainly welcome.

Open the application information property list, usually named ‘Info.plist‘, in your project and follow these steps…

1. Update the bundle version format

First, update the format of the ‘Bundle version’ entry (CFBundleVersion) to contain exactly 3 period-separated integers representing the version number (e.g., “1.01.1“).  It cannot contain alphabetic characters (and although some documentation suggests that it may contain more or fewer integers, we did not take that chance).

For non-MAS applications, the format of this field was not enforced and, in fact, the default ‘About’ box encouraged the use of this field as a standard version description (alphanumeric string) by directly displaying it underneath the application name.  We used a format like, “1.01 (January 2012)”, which is more useful and aesthetically pleasing, but this was cause for rejection.

2. Add an application category

If you do not have one already, you will need to add an ‘Application Category’ entry (LSApplicationCategoryType).  The easiest way to set this value (in Xcode 4) is to select the ‘Summary’ tab for your target and select the appropriate setting in the ‘Application Category’ box.  In the case of Pretty Good Solitaire, we chose ‘Games – Card Games’ (public.app-category.card-games).

Note that Xcode 3 did not recognize this key, so it was necessary to explicitly add it, along with the appropriate category value, as found in the Information Property List Key Reference; fortunately, this is no longer necessary.

3. Set the minimum system version

Next, set the ‘Minimum system version’ entry (LSMinimumSystemVersion) to “10.6.6”, or higher if appropriate.

The Mac App Store does not work on versions of Mac OS X prior to 10.6.6 anyway, and leaving this at a lower setting (even if your downloadable versions support Leopard, Tiger, or even an earlier OS) may be cause for a rejection.

4. Review the supported document types

Finally, review the supported ‘Document types’ entry (CFBundleDocumentTypes), if any.  Remove any document types that will not be supported in your store version.

In our case, we supported a document type for saved games, which is still useful, but also a document type for automatic installation of extra card sets (which can be downloaded), or in the case of Pretty Good MahJongg, types for both extra tile sets and tile matching layouts.  Since downloading or installing any improvement to your application (outside of the Mac App Store) is verboten, we needed to remove this support.

Note that this initially passed muster with our first product, but it was cause for a rejection later on a different product using essentially identical functionality.  There is clearly some subjectivity to the application reviews, so a more thorough (or nitpicky) reviewer may find something previously allowed.  When a rejection can set your release schedule back a couple of weeks or more, it is not worth the risk.

Conclusion

With just these few changes to your information property list, your project should have the necessary application information for submission.  In the next installment, Part 3: Data and Resource guidelines, I will describe the issues you may encounter with your application data.

MAS Preparation, Part 1

Project modifications

In Preparing for Mac App Store Submission, the first set of changes you should make are to the project itself.

This installment describes the project modifications that need to be made to an existing Mac OS X game project.  The general assumptions are that the existing project is working and properly tested, and that, ultimately, you will want to maintain a single set of source code with conditional compilation to differentiate the store version from other builds.  Note that these are the steps that we took for Pretty Good Solitaire Mac Edition; your project may require some adjustments to these steps.  (Comments where any significant change is necessary would be very appreciated.)

So, without further ado…

0. Create a duplicate store project

Before making any other changes, create a duplicate copy of the entire project folder and name the copy appropriately.  In our case, the original folder was ‘Pretty Good Solitaire’ (which builds full and trial versions of the game) and we created a separate ‘pgsse’ (Pretty Good Solitaire [Mac/]Store Edition) folder for MAS modifications.

The version of your project that you will submit to the Mac App Store is a separate SKU (Shelf Keeping Unit), a build that uses slightly different code and configuration and which is distributed via a different channel.  While it is possible to have the store target within the main project, certain features (e.g., Power PC support, Mac OS X 10.5 support, downloadable data) are not supported in MAS, so it is easier to separate them (at first, anyway).  In any event, doing so at the start gives you a safe playground for making changes without messing up your working project.

1. Update the project version number

As just noted, the store build is a separate version and, thus, should have a different version number.  In our case, we decided that odd minor versions (e.g., “1.01”) would represent the store editions, while even minor versions (e.g., “1.00”) represented the direct downloadable editions.

2. Rename the primary build target

In the new project (of course), rename the primary build target to something appropriate.  In our case, we renamed the full version target to ‘Pretty Good Solitaire store’, which is now the store version.  You could also delete any redundant or obsolete targets remaining in the project.  For example, we deleted the trial version target, as it is built in the original project and the MAS version cannot have any vestiges of a trial version.

Note that this step is not strictly required, but it is a good idea to differentiate between targets, so it is always immediately obvious which project is active, and also to minimize any excess baggage, which reduces the possibility of mistakes.

3. Build with a current Xcode version

Make sure that you build the project with a current version of Xcode.  Submissions to the Mac App Store now require Xcode 4 and, as of this writing, the latest version is Xcode 4.2.1.

If you have an older version of Xcode, this would be a good time to upgrade, and although it will not be mentioned explicitly, you should build the project regularly, ideally after every change, to make sure that the build is not broken and behaves as expected.

4. Define a preprocessor variable

To allow for conditional compilation of certain source code, it is a good idea to define a preprocessor variableAPPSTORE, for any build targets intended for MAS.  In the ‘Build Settings’ for the target (or the whole project, if you prefer), find the setting for ‘Preprocessor Macros’ and add “APPSTORE” to each configuration.  Note that it is common to have different variables for ‘Release’ and ‘Debug’ configurations, so be careful to define APPSTORE for each one without accidentally removing or altering any existing definitions.

Of course, there is no requirement that the preprocessor variable be named “APPSTORE”, but beware that simply using “STORE” results in a naming conflict in the latest Mac OS X SDK.

5. Add necessary frameworks/libraries

In order to test the validity of app receipts, you will need to add the IOKit and Security frameworks and the crypto library.  From the ‘Build Phases’ of the primary target, open the ‘Link Binary With Libraries’ section and, by clicking on the ‘+’ symbol, add ‘IOKit.framework‘, ‘Security.framework‘ and ‘libcrypto.dylib‘.

Note that Xcode 4 adds these frameworks/libraries at the top level of your project; you will probably want to drag them into the ‘External Framework and Libraries’ folder with the other frameworks.

6. Configure debugging symbols

Despite submitting a release version to MAS, Apple requires debugging information to be included with a submission.  To accede to this requirement, you must set ‘Generate Debug Symbols’ to “Yes” and also set ‘Debug Information Format’ to “DWARF with dSYM File” (at least for the ‘Release’ configuration) in the ‘Build Settings’ of the target.

In our original project, we had all debug information disabled and/or stripped from the release builds, but one of our early issues was the lack of the dSYM file with debugging information for Apple.

7. Set correct build architecture

Finally, set ‘Architectures’ to an Intel (only) setting; for our project, that is “32-bit Intel”.

Even if your code and original project supports both PPC and Intel via a “Universal” application, the presence of a PPC build in your submission will result in rejection.  (We found that out the hard/lengthy way.)  At least now there are settings for this; in Xcode 3, you had to use “i386”, which was not even listed as a choice.

Conclusion

At this point, you should have a new project with a store target and all of the build settings configured appropriately.  In the next installment, Part 2: Property List (Info.plist) changes, we will discuss the necessary adjustments and additions to the information property list for your project.

Preparing for Mac App Store Submission

Making a Mac OS X game project suitable for MAS

If you currently have a Mac product and have not already done so, you may be considering submission to the Mac App Store (MAS).

In the upcoming series of posts, I will be detailing the process that we went through to get Pretty Good Solitaire Mac Edition, and some of our other game products, successfully submitted to MAS.  There were a number of rejections along the way, as the App Store Review Guidelines [note: requires Mac developer agreement], while extensive, are not comprehensive (nor are they 100% consistent, as we had some products accepted and others rejected with identical behaviors).

Over multiple submissions, and fewer rejections, we developed a submission checklist which I will detail roughly (some items are specific to our games) in these upcoming posts:

We have had product in the Mac App Store since launch day, more than a year ago.  If you already have a game that runs on Mac OS X, it makes sense to make the several modifications to get it into MAS, another channel to find customers.  However, in our experience, it is not a viable substitute for direct downloadable sales.  The channel is not (yet) the primary ‘go to’ location for Mac software, although the availability of Lion (Mac OS X 10.7) only on MAS should shift more customers.  Additionally, there is the same downward pressure on pricing (towards free) seen on the iOS App Store, sales are lackluster, and (of course) you are giving 30% directly to Apple.

I would certainly not recommend developing a project solely for the Mac App Store, nor eliminating a direct downloadable sales channel in favor of MAS, but with an existing project it may be worth the fairly limited extra effort it takes to be there, too.

Objective-C: @property gotcha #1

Sometimes “best” practices can bite you.

In Apple iOS documentation, they strongly recommend the use of declared properties to automatically generate access methods to class variables.  In header files, you would have something like this:

@interface MyClass
{
    IBOutlet UIView* view;
}

@property (nonatomic, retain) IBOutlet UIView* view;

@end

 

Technically, this generates access methods named ‘view’ and ‘setView’, but in practice one generally accesses the class variable with the dot notation (i.e., ‘self.view’) .  The implementation of this class (minus any explicit methods) would be:

@implementation MyClass

@synthesize view;

@end

 

Accessing the variable with dot notation calls the access methods (as does calling them explicitly, obviously), but simply using ‘view’ (without the ‘self’ reference) accesses the variable directly, omitting any other functionality associated with the accessors, such as (in the above example) retaining the new view.  This is generally a poor practice except in initialization and deallocation routines, where it is preferred.

So, in order to assure that one does not accidentally skip the accessors, the recommended best practice is to use the ability of @synthesize to generate accessors that access a slightly different variable name.  In other words, instead of ‘view’ and ‘setView’ referencing the ‘view’ variable, they can be instead made to access ‘view_’:

@synthesize view = view_;

 

This is, in theory, a good idea because one can only access the variable directly with the explicit addition of an underscore (in this case), and simply referencing ‘view’ instead of ‘self.view’ should produce a compiler error.  (Note that we use a trailing underscore because leading underscores already have a specific meaning in our coding guidelines.)

Problem: If you modify the class implementation as noted above to put this into practice, you introduce a bigger problem into your code.  It turns out that @synthesize actually creates a class variable if none of the specified name exists, but it does not generate a warning or error if the one of the ostensible name does exist.  In other words, the above line would create a new ‘view_’ class variable, and create accessor methods, despite the fact that ‘view’ already exists.  The ‘view’ and ‘setView’ methods modify ‘view_’, so ‘self.view’ does the same, but failing to ‘self’ reference, rather than generating the intended error, actually modifies the orphaned ‘view’ variable.  Instead of having an extra compiler check, you instead have two very similar variables in the same class and any error becomes even harder to diagnose.

If the @property/@synthesize combination essentially replaces normal variable declarations, it obviates the whole issue of these declarations.  This seems rather silly/weird, since declaring [class] variables is a staple of C[++], and the method of doing this in Objective-C is one of the first lessons taught.  Nevertheless…

Solution: To make this idea an actual best practice, at least for simple classes, omit the entire parenthesized section of the class declaration and just declare all variables via @property/@synthesize statements.  You would end up with something like the following:

@interface MyClass
@property (nonatomic, retain) IBOutlet UIView* view;
@end
@implementation MyClass
@synthesize view = view_;

- (id)init
{
    self = [super init];
    if ( self )
    {
        view_ = nil;
    }
    return self;
}

- (void)dealloc
{
    [view_ release];
    [super dealloc];
}

@end

 

All (or most) other references to the class variable would be via dot notation, ‘self.view’, which would (of course) modify the ‘view_’ variable via accessors, as desired.

Happy coding!

Ten Little Images (or so), Part 2

Making sense of launch image requirements for iOS universal applications.

When developing a “universal” application for iOS, an app that will run on all (current) iOS devices, one of the first things you have to consider are the initial branding graphics for your game. These include the launch images for each device (and orientation), in addition to the application icons.

The first part of this article dealt with application icons for a universal iOS app.  This part concerns the launch images, which are static full-screen graphics displayed by iOS itself while the app is loaded and initializes itself, before it has any opportunity to show other graphics.

On an iPad, your application could start in any of four different orientations, two vertical (portrait) and two horizontal (landscape), so you will want one portrait (iPad) launch image and one landscape launch image.  (Technically, you can specify a different launch image for each of the four orientations, but it seldom, if ever, makes a difference beyond portrait or landscape.)  On an iPhone or iPod touch, an application only launches in a portrait orientation, with the home button at the bottom, but these smaller devices may (or may not) have a Retina display, so you need to provide both a normal portrait launch image and a high resolution version.

The purpose of launch images is to provide immediate visual feedback to the user when an application icon is tapped.  Apple’s iOS Human Interface Guidelines document, which is very good in many respects, recommends that the launch image be identical to the first screen of the application, or even simpler, omitting information that is not guaranteed static.  For a game, however, ignore this advice; the launch image is a defacto splash screen, so rather than being simple and unobtrusive, launch images for a game application should be eye-catching.  (We actually do create a “first screen” that replicates the launch image, but can smoothly add information such as version number and build/release date.)

Again, the assumptions here are that you are creating a “universal” application, supporting iOS 3.2 (the minimum version for iPad), and want to be sure to have your branding artwork shown in the best light on all three types of devices. If you are supporting only iPad (no small screens or Retina displays) or only iOS 4+ (no backwards compatibility), then there are fewer conflicts and caveats, but this article should still be helpful.

Launch Image Artwork Specifications

All launch images (and icons) must be in PNG format (24-bit), with no transparency.  The naming conventions for launch images, specifying which graphics to display on each device and supported orientation, are more restrictive than for icons.  In fact, the default launch image base name is (unimaginatively) “Default”.  For somewhat more descriptive naming, we use the project name (“DemolishPairs” herein) as the base name, though the modifiers are mostly fixed (and somewhat ugly).

For a complete set of launch images, we have the following (4) launch image files:

  1. DemolishPairs-Portrait.png [768×1004] – This is the launch image for portrait orientations on the iPad.
  2. DemolishPairs-Landscape.png [1024×748] – This is the launch image for landscape orientations on the iPad.
  3. DemolishPairs~iphone.png [320×480] – This is the (portrait) launch image for the older iPhone and iPod touch.
  4. DemolishPairs@2x~iphone.png [640×960] – This is the (portrait) launch image for newer iPhone and iPod touch devices with a Retina display.  (It is also the ugliest required filename, but at least it is better than ‘Default@2x~iphone.png‘.)

Note that the portrait restriction for non-iPad devices is limited only to launch images; universal applications can (and usually should) support all four orientations, portrait and landscape, on iPhone and iPod touch devices.  For other background graphics, there are usually six different images: portrait and landscape each for iPad, iPhone, and iPhone (Retina) devices.

Project Configuration for Launch Images

Once you have the launch image artwork, it is necessary to include all of these files in the Xcode project, so they will be copied to the compiled bundle.  If you choose to use the ‘Default’ naming, this is all that is required.  However, we chose to use a different base file name, so we have to add a ‘Launch image‘ (UILaunchImageFile) string entry, with the value “DemolishPairs“, to the project’s ‘Info.plist‘ file.

Caveat #1: Xcode 4 allows you to drag launch image files to the ‘Summary’ page of a target’s configuration, and it will automatically add these files to the project.  Unfortunately, Xcode only understands the ‘Default’ naming, so it will name the iPad launch images ‘Default-Portrait~ipad.png’ and ‘Default-Landscape~ipad.png’.  These names are invalid on iOS 3.2, which does not recognize the ‘~ipad’ modifier for launch images, so if you use this shortcut and default naming, you still need to remove the “~ipad” part of each filename for backwards compatibility.

Corollary: Choosing not to use the default base file name for launch images (i.e., adding a valid UILaunchImageFile entry) causes Xcode to become confused and show no launch images on the ‘Summary’ page.  Our recommendation is to edit directly on the ‘Info’ page and ignore the ‘Summary’ page altogether.  (Xcode also has trouble with the “pretty” property values if the .plist file ends with anything other than “Info.plist“.)

More observant readers may have noticed that the two iPad launch images allow 20 pixels for the status bar (on the top), while the iPhone/iPod touch do not.  In order for those launch images not to lose 20 points (20 pixels for non-Retina, 40 pixels for Retina displays) hidden underneath a status bar, you need to hide the status bar on launch.  This is done by adding a ‘Status bar is initially hidden‘ (UIStatusBarHidden) boolean entry set to YES.  (Of course, you could compensate with the artwork, too, I suppose.)

Caveat #2: Hiding the status bar works fine for iPads running iOS 3, which (correctly) just turns the reserved status bar area black, displaying the launch image correctly regardless.  Unfortunately, iOS 4 ill-advisedly attempts to use the entire screen when the status bar is hidden, thus invalidating all of the Apple recommendations for launch image size.  The result is a stretched launch image which, because aspect ratio is preserved, extends off the right edge of the screen.  The only way to make launch images behave the same on all iPads is to not hide the status bar.  Fortunately, this can be done without invalidating the previous change by adding an iPad specific version of the property, UIStatusBarHidden~ipad, and set its (boolean) value to NO.  (Xcode itself does not understand the setting, so it has no “pretty” name, but iOS handles it just fine.)

Caveat #3: When entering property names for the Info.plist, especially for those specific to iPad (or iPhone), note that the names are case-sensitive.  In particular, the modifier is “~ipad” (or “~iphone“); if you capitalize the ‘P’ out of habit, the entire property will be ignored (on any device).

Technical notes:  The above information has been thoroughly tested using Xcode 4.0, specially created launch images, and both the iOS Simulator and a variety of physical devices.  The launch images were designed to be distinguishable from each other, with single pixel borders for detecting stretching and clipping.  Results were confirmed for iOS 4 on the simulator for all three types of devices: “iPad”, “iPhone”, and “iPhone (Retina)”, as well as on an original iPad (iOS 3.2), a second generation iPod touch (iOS 4.2.1), an iPhone 4 (iOS 4.2.6), and an iPad 2 (iOS 4.3.5).  [Editor’s note: We have no plans to upgrade any device to iOS 5.x in the immediate future.]

Making sure that your application icons and launch images look great is an early step in creating a compelling game experience, and I hope that both parts of this article help you develop a universal iOS application without falling victim to one of the potential iOS pitfalls with your branding graphics.  As always, questions and comments are happily accepted.

Ten Little Images (or so), Part 1

Making sense of icon image requirements for iOS universal applications.

If you are developing (or considering) a “universal” application for iOS, an app that will run on all (current) iOS devices, one of the first things you have to consider are the initial branding graphics for your game.  These include the icons, in various sizes, and the launch images for each device.

The icons, of course, are displayed on the home screen of the device to represent the game, but they can also be shown (in different sizes) on the search page (as well as in Settings, if appropriate).  The launch images are stand-in graphics that are displayed in a static fashion while the app is loaded and initializes itself.  On an iPad, there need to be launch images for each orientation (portrait and landscape), while the iPhone and iPod Touch only launch in portrait orientation.  For more variety, though, the iPhone 4 and 4th generation iPod Touch have the Retina displays, with higher resolution, requiring still more images.

The assumptions here are that you are creating a “universal” application, supporting iOS 3.2 (the minimum version for iPad), and want to be sure to have your branding artwork shown in the best light on all three types of devices.  If you are supporting only iPad (no small screens or Retina displays) or only iOS 4+ (no backwards compatibility), then there are fewer conflicts and caveats, but this article should still be helpful.

Icon Artwork Specifications

All icon (and launch) images must be in PNG format (24-bit), with no transparency.  Although there are naming conventions for automatically loading different files according to the device type, arbitrary (descriptive) file names for icons are preferred and more reliable.  In our case, we use the project name (“DemolishPairs” herein) as a base name, with “ipad”, “iphone”, and “retina” used as modifiers.

For complete icon coverage, with no scaling performed by iOS, we have the following (8) icon files:

  1. DemolishPairs.png [512×512] – This is the largest (current) icon size for iOS applications; generally, the artwork should begin at this size (or larger) and be scaled down to the other sizes.
  2. DemolishPairs_ipad.png [72×72] – This is the application icon for the iPad, as shown on the home screen.
  3. DemolishPairs_ipad_small.png [50×50] – This is the application icon for iPad, displayed in search results.
  4. DemolishPairs_iphone.png [57×57] – This is the application icon for the older (non-Retina) iPhone and iPod touch.
  5. DemolishPairs_iphone_small.png [29×29] – This is the search results icon for the older iPhone and iPod touch.
  6. DemolishPairs_retina.png [114×114] – This is the application icon for the newer (Retina) iPhone and iPod touch.
  7. DemolishPairs_retina_small.png [58×58] – This is the search results icon for iPhone/iPod touch with Retina displays.
  8. iTunesArtwork [512×512] – This is (in our case) a copy of ‘DemolishPairs.png‘ with a very specific filename (note: no file extension, not even ‘.png’) for ad-hoc distribution and/or submission to the App Store.

Note that most games will not have Settings packages, but those that do can use the 29×29 icon [5] for all older displays, including iPad, and the 58×58 icon [7] for all Retina displays.  (Document icons have different requirements but are generally unnecessary for games, so they are not covered here.)

Project Configuration for Icons

Once you have the icon artwork, it is necessary to include all of the icon files in the Xcode project, so they will be copied to the compiled bundle, and then modify the project’s ‘Info.plist‘ file (by whichever name) to indicate the icon image filenames.  There are two possible entries that indicate icons, and since we are specifying multiple image files (and by Apple recommendation), we will add an ‘Icon files‘ (CFBundleIconFiles) array with six entries:

  • DemolishPairs_ipad.png
  • DemolishPairs_ipad_small.png
  • DemolishPairs_iphone.png
  • DemolishPairs_iphone_small.png
  • DemolishPairs_retina.png
  • DemolishPairs_retina_small.png

Caveat:  ‘DemolishPairs_ipad_small.png‘ must appear before ‘DemolishPairs_iphone.png‘ in the list; otherwise, iOS 3.2 (iPad) will incorrectly select the 57×57 icon instead of the 50×50 icon when displaying search results.

Although the CFBundleIconFiles array takes precedence, there is still a minor reason to add the (singular) ‘Icon file‘ (CFBundleIconFile) string, with “DemolishPairs.png” as the value.  Xcode 4 uses this image file as the default icon for the target application in the project; if it is missing or empty, the last entry in the array is used.  This (currently) has no practical impact on the application itself, but supplying a reference (512×512) icon within the bundle is not a bad thing.

Of course, if one is building an application for only iPad devices, the number of icons necessary is reduced, but I would still recommend getting a complete set of the above icon sizes from your artist anyway (just in case).  On the other hand, if one is building an application for only iPhone devices, shame on you; there is no excuse for not supporting the iPad nowadays.

Technical notes:  The above information has been thoroughly tested using Xcode 4.0, specially created test icons, and both the iOS Simulator and a variety of physical devices.  The icon images were designed to be distinguishable from each other, with single pixel borders for detecting stretching and clipping.  Results were confirmed for iOS 4 on the simulator for all three types of devices: “iPad”, “iPhone”, and “iPhone (Retina)”, as well as on an original iPad (iOS 3.2), a second generation iPod touch (iOS 4.2.1), an iPhone 4 (iOS 4.2.6), and an iPad 2 (iOS 4.3.5).  [Editor’s note: We have no plans to upgrade any device to iOS 5.x in the immediate future.]

In our next installment, Ten Little Images (or so), Part 2, I discuss the requirements and caveats of launch images in universal iOS applications.

Carbon nibs update

A spurious warning appears to be spurious.

In my last post, Carbon nibs under Lion, I gave a solution to the problem of Carbon nib (interface) files not being supported in Xcode 4, while Xcode 3 would not run under Mac OS X 10.7 (Lion).  That solution was to run Interface Build 3.2.6 and convert the nibs to a newer format.

Toward the end of the post I mentioned that many windows in the converted nib files produced a warning: “This window’s content rectangle does not lie entirely on the screen with the menu bar and may not be completely visible for all screen resolutions and configurations.”  In testing, these files did not exhibit any errant behavior, but shipping a product, even a beta, with build warnings is against our development guidelines.

Since that post (and in preparation for a proper build, without warnings), I did a little research and experimentation and discovered that the problem appears to be a minor issue with the conversion, where the resulting data is aberrant enough to generate a warning, but is handled correctly in the resulting application.  Although I did not dig deeply enough to identify the exact source of the problem, it is related to window positioning (as one may have guessed).

The solution, oddly, is simply to open the offending nib file, select the (or each) window, click on the Size (ruler) tab in the Inspector, and then drag the window position image, even slightly.  As far as I can discern, any movement (within the simulated window) fixes the problem; at least, it fixed it for all of my affected windows.  Clearly, the size of the windows was not the issue, since that was not changed, and the position should never have been a problem, either, for windows with the ‘Center’ attribute enabled (as most of mine were).  I also note that the windows I created from scratch since moving to this Lion/IB 3.2.6 setup were unaffected.

One other idiosyncrasy to note is that the build process also produces the following message: “View is clipping its content.”  It is not a warning, just a message, and I assumed that it was related to the above warning until the warnings were fixed.  It is a straightforward message, albeit with no reference to the specific view involved, so I looked into find the problem there as well.

As it turns out, there is a very useful tool with IB 3.2.6 to assist with this.  Select ‘Layout->Show Clipping Indicators’ to enable a feature that displays a small “+” at the bottom of any view that is clipping its content.  I never noticed this setting before, and it can be very handy.  Alas, it also reveals (in our case) that the messages are just pointless chatter, since they are being given for list views with extra columns that are intended to scroll horizontally.  Fortunately, they do not produce a warning message, so the messages are easily ignored; in fact, they only appear on the full build log, so I may have never noticed them had I not been debugging a nearby warning.

[The most meaningful comment that I received for the last post was (seriously), “I’ve a cockroach on my pillow.  Wanna see it?”  The days of technical development posts may be numbered.]