Showing posts with label runtime. Show all posts
Showing posts with label runtime. Show all posts

Saturday, April 20, 2013

Tutorial 29 - Codea v1.5.2: Objective C Add On, iAds


Figure 0. Codea implementing iAds - showAdFromTop()

29.1 Overview


CodeaAddon is an experimental protocol for adding native extensions to exported Codea projects. You must deal with Lua directly to register your functions and globals. This protocol should be considered alpha and is subject to change in future Codea releases.

With that disclaimer out of the way, let's have a look at what we can do with this new functionality. We have previously done tutorials to add Game Center and iAd functionality using the old runtime but with the great new export to Xcode functionality, this is no longer the best way to skin that particular cat.

You may want to re-read our previous tutorial on implementing iAds in Codea as we won't cover the same background in this tutorial.

We will build on the previous tutorial which uses the audio add on. This has the added benefit of showing how you can stack a number of add ons to the same project.

Note that before you start adding advertising support to your applications available on iTunes, you must first agree to the iAd Network agreement. Further, you must explicitly enable iAd for each application in iTunes Connect. As a part of the iAd Network, you control the kinds of ads that are delivered to your application. We don't need to do this to test it in the simulator though.


Figure 1. Add the iAd Framework to your App



29.2 Add the iAd Framework to your App


Fire up Xcode and load the exported version of your Codea application (See Tutorial 27). Click on the imported project file at the top of the project navigator then in the Build Phases tab, scroll down to the link binary with libraries area and select the drop down arrow. Click on the "+" button below your existing frameworks to add a new framework. Find iAds and click on "Add" (Figure 1).


29.3 Update the AppDelegate Files


In the AppDelegate we need to register our new add on classes. The new AppDelegate.h file now looks like:


//
//  AppDelegate.h
//  AudioDemo
//
//  Used to demonstrate the audio add on and iAds add on libraries
//
//  Created by Reefwing Software on Sunday, 14 April 2013
//  Copyright (c) Reefwing Software. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "AudioAddOn.h"
#import "IAdsAddOn.h"

@class CodeaViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) IAdsAddOn *iAdsAddOn;
@property (strong, nonatomic) AudioAddOn *audioAddOn;
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) CodeaViewController *viewController;

@end


And similarly to what we had in the previous tutorial AppDelegate.mm now looks like:


//
//  AppDelegate.mm
//  AudioDemo
//
//  Created by Reefwing Software on Sunday, 14 April 2013
//  Copyright (c) Reefwing Software. All rights reserved.
//

#import "AppDelegate.h"
#import "CodeaViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[CodeaViewController alloc] init];
    
    //  Create and add our AudioAddOn to Codea
    
    self.audioAddOn = [[AudioAddOn alloc] init];
    [self.viewController registerAddon: self.audioAddOn];
    
    //  Create and add our iAdsAddOn to Codea
    
    self.iAdsAddOn = [[IAdsAddOn alloc] init];
    [self.viewController registerAddon: self.iAdsAddOn];
    
    NSString* projectPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"AudioDemo.codea"];
    
    [self.viewController loadProjectAtPath:projectPath];
    
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
}

- (void)applicationWillTerminate:(UIApplication *)application
{
}

@end



29.4 The iAds Add On


Our iAds add on implements two internal booleans, isBannerVisible and showBannerFromTop. Hopefully the use of these should be fairly obvious. We also register three new functions for use within Codea:


  1. showAdFromTop();
  2. showAdFromBottom(); and
  3. hideAd()
Our example project demonstrates the use of all 3 of these functions. We start by displaying Ads from the top of the page (once the ad has been loaded from the ad server). We hide ads when the play button is tapped and then show them from the bottom when the stop button is tapped.

In the simulator apple will send you ad errors regularly (e.g. Ad inventory unavailable) to make sure that your code can handle this. Your app will get rejected if it displays an empty ad banner so the add on takes care of this situation. When displaying the ad banner, it will slide down from the top or up from the bottom depending on which function that you have used. Similarly hideAd() will animate the ad sliding above or below the screen depending on the state of the boolean showBannerFromTop.

Figure 2. Codea implementing iAds - showAdFromBottom()


This example add on only handles ads for an iPad in portrait orientation. We have included device detection macros in IAdsAddOn.h, just remove the comment slashes if you want to use these to position your Ads. To handle different orientations and devices update the banner view frame variables in the two methods:
  1. - (void)showBannerViewAnimated:(BOOL)animated; and
  2. - (void)hideBannerViewAnimated:(BOOL)animated.

If you don't want the banner views to slide to the new position then set animated = NO for the above two methods.

29.5 Download the Code


The complete code listing is available below.




Saturday, November 17, 2012

Tutorial 23 - Implementing iAds with Codea


23.1 Introduction


A common business model in the App store is to give away your app for free and generate revenue by serving ads to your application. This model has benefits but can annoy your users if done in excess. Everyone likes stuff that is free, so setting a zero cost removes most of the barriers to downloading your app and should maximise download numbers.

Since iOS 4.0 the iAds framework has been available for developers. Using this you can add banner or full screen advertisements to your application. If you are planning to include ads on a screen then you need to ensure that you have left space within your interface to display them. Full screen ads (referred to as interstitial ads by Apple) are only available on the iPad and are only suitable in certain situations, so we wont cover those in this tutorial.

You receive revenue when users view (called impressions) or click advertisements on your app. Some apps use a bit of social engineering to maximise their click through rate. For example the Foxtel (cable TV) app in Australia has ads which appear at the top of the channel selection screen. As per the Apple guidelines these ads are only displayed once the banner has been loaded from the ad server. When this occurs, the ad slides in from the top and moves the content down by the height of the banner. However what happens 50% of the time (for us at least) is that you accidentally tap the ad when you are trying to select a channel.

It is difficult to estimate exactly what revenue you might receive from including iAds in your app. A graph of the impressions that we got for the last year is shown below. There was about 98k in total with 90% coming from one app (Personality). According to Apple the effective revenue per thousand ads (eCPM) served over this period was $0.82. In practice, we get on average $0.25 per day. So while this may not be a get rich quick scheme, it is not bad passive income, particularly given the app I'm deriving revenue on is not optimised for ads. 

We suspect you could do much better with a free game app with high reusability (people tend to use Personality only 2-3 times at best). Apple says that "hundreds of developers are making more than $15,000 per quarter". Given that there are 275,000 iOS developers in the US alone, this is perhaps not that impressive - albeit not all of those developers have iAd enabled apps.




23.2 Banner Views


From a Codea perspective, implementing iAds is easy. If you are happy to display ads on every screen then you just need to leave the appropriate amount of space on your screen to display the ad. In most cases there will be screens that you don't want to display ads on (e.g. the main game screen), so we have extended Codea Lua with a function, showBannerAd(true) to turn ads on and off. For our example, we will only display ads on the Menu and High Score screens.

For the iPad, banner sizes are set at:
  • Portrait: 66 (height) x 768 (width) points - see Interlude 13 if you dont understand the difference between pixels and points.
  • Landscape: 66 (height) x 1024 (width) points.
For completeness, the iPhone banner sizes are 320 x 50 points for a portrait advertisement and 480 x 32 points for a landscape advertisement.

The banner ads are intended to typically appear either at the top or bottom of the display and are provided in two formats so that ads may be displayed when the device is either in portrait or landscape orientation.


23.3 Setup iAds in iTunes Connect


As with Achievements and in-App purchasing, there are some things that you need to enable in iTunes Connect before your app will be able to receive ads from Apple's servers. Log in to your developer account, select iTunes Connect and then click on Manage your Apps. Click on the appropriate App icon and then click on the Setup iAds link (right hand side towards the top).

Answer the question regarding whether the primary target audience for your app is users under 17 years of age and then click Enable iAds and Save.

That's it! You can disable iAds just as simply but changes to your iAd settings will not take effect until your next app version is approved.


23.4 Creating Your Banner Views in the Codea runtime


You should only create a banner view when you intend to display it to the user. Otherwise, it may cycle through ads and deplete the list of available advertising for your application. As a corollary to this, avoid keeping a banner view around when it is invisible to the user. To demonstrate the implementation of iAds in the runtime we will use our old faithful MineSweeper application.

Based on our careful UI planning (or perhaps just through good luck) we happen to have enough space at the top of the MineSweeper Menu screen to fit in a banner ad, so that is where we will put it. As MineSweeper is now a universal application we will need to handle the iPhone sized banners as well. We have more room at the bottom of the iPhone Menu screen when it is in the portrait orientation, so when we detect that device and orientation we will place the banner at the bottom of the view. There is no room for a banner on an iPhone in landscape orientation, so we will disable ads when we detect this combination.

Banner views use a delegate to communicate with your application. Your application will thus need to implement a banner view delegate to handle common events. In particular we need to handle:
  1. when the user taps the banner.
  2. when the banner view loads an advertisement.
  3. when the banner view encounters an error.
Usually you would place this code in the relevant view controller but for simplicity we will handle this in the CodifyAppDelegate (the alternative is to extend the BasicRendererViewController class in the runtime).

If your application supports orientation changes, your view controller must also change the banner view’s size when the orientation of the device changes.

Step 1 - Add the iAd Framework to your App.

Fire up Xcode and load the runtime version of your Codea application. Click on the CodeaTemplate file at the top of the project navigator then in the summary tab, scroll down to the linked libraries area. Click on the "+" button below your existing frameworks to add a new framework. Find iAds and click on "Add".

Step 2 - Update the CodifyAppDelegate Files.

In CodifyAppDelegate.h you need to import the framework you just added using:

#import <iAd/iAd.h>

then modify the class interface definition so that it looks like this:

@interface CodifyAppDelegate : UIResponder<UIApplicationDelegate, ADBannerViewDelegate>

This indicates that the ADBannerViewDelegate protocol will be implemented. We will provide a link to download the updated CodifyAppDelegate files below. We have added two other things to the CodifyAppDelegate files:
  1. A boolean instance variable called displayingAds which is controlled from your Lua code via the modified aGameCenter_Codea class; and
  2. A call back method called iAdDisplayStatusChanged which is used to update the banner view if the MineSweeper game state or orientation changes. This also comes via the modified aGameCenter_Codea class.
Step 3 - Update the other Codea runtime Files.

As we saw in Tutorial 19 when integrating Game Center, there are changes required in LuaState.m, OSCommands.h and OSCommands.m, to allow Lua to communicate with our Objective C code. This mostly comprises registering our new showBannerAd(true or false) function.

In LuaState.m add the following to the  - (void) create method:

    //iAds Function
    LuaRegFunc(showBannerAd);

In OSCommands.h add the following below the similar Game Center definitions:

    //iAds
    int showBannerAd(struct lua_State *L);

Finally, in OSCommands.m add the following method below the Game Center definitions:

int showBannerAd(struct lua_State *L){
    [CodeaGameCenter showBannerAd:lua_toboolean(L,1)];
    return 0;
}

23.5 Codea Lua Code Changes


As mentioned in section 23.2, if you are happy to display adds on every screen then there is no changes required to your Lua code (assuming you left space for the ads). If like us you want to select when ads are displayed, then you need to use the new showBannerAd() function. If you pass true in this function then ads will be displayed and if you pass false, they wont.

As an example, the following shows our updated orientationChanged() function. 

function orientationChanged(newOrientation)

    print("Orientation Change Detected.")
    
    if setupHasRun and gameState == stateRun or gameState == stateWon or 
        gameState == stateLost then
            updateGridLocation()
    end 
    
    if setupHasRun and (gameState == stateMenu or gameState == stateScore) then
        showBannerAd(true)
    else
        showBannerAd(false)
    end
    
end

We also use showBannerAd()  when the gameState changes due to button taps.

The other class we need to modify is the SpashScreen. In the fadeAnimation call back, we turn on ads once the splash screen has faded away.

function fadeAnimationDone()
    
    -- Call back function for Fader complete
    
    gameState = stateMenu
    showBannerAd(true)
    
end

23.6 Download the Updated Runtime & Codea Files


The aGameCenter_Codea and CodifyAppDelegate files are available on GitHub. In addition, the following links allow downloading individual files from DropBox:

Saturday, August 18, 2012

Tutorial 13 - Submitting to the App Store Part 2

    

13.1 Some Runtime Things to Watch


Further to part 1 of this tutorial, there are a couple of things, which if you are not aware of them, can cause problems with running your Codea App in the runtime.

13.1.1 Using Version in the pList

The runtime expects your version variable to be a string. So if you set a version number in Codea using something like saveProjectInfo("Version", version), where version is a number then you will get an error when you try to compile your project.
  
The solution is to either delete this line in your code or to modify a line in the runtime objective C code. If you want to take the second option then in the CodifyAppDelegate class go to the - (NSString) versionForProjectAtPath:(NSString)path method and change the line:
   
NSString* version = [infoPlist objectForKey:@"Version"];
   
To:
   
NSString* version = [[infoPlist objectForKey:@"Version"] description];

   
If you are using a float to represent your version (e.g. 1.4) then it is likely that within the info.plist file (which is found in the Project.codea folder) that this wont be the number you  are expecting (e.g. you get 1.39999999999234 instead of 1.4). This is due to the size of the memory allocated to store numbers in Codea. Anyway, just edit this in your pList file in Xcode back to what it should be. Note that there are two info.plist files, one for your App (found in classes -> Supporting Files) and one for your Codea project.
    
13.1.2 Supporting Orientations

Another trick for young players is that the function orientationChanged(newOrientation) is called before the setup() function in Main. So if you use global variables which are defined in setup() in the orientationChanged() function you will get a runtime error because they haven't been defined yet.

If you are in this situation, the solution is a three step process:

1. In Main, add the following line before anything else:

setupHasRun = false

-- Other global stuff

2. Then in your setup() function, once your setup is done set the variable to true:
  
function setup()
    
    -- setup stuff
  
  setupHasRun = true
      
end
 
3. Finally in the orientationChanged() function:

function orientationChanged(newOrientation)

    if setupHasRun then
        -- Your existing orientation code
    end

end


And that should sort out the problem. Thanks very much to Simeon from Two Lives Left for tracking this solution down.

     

13.2 Customising the Runtime


     
Before submitting your App to iTunes, there are a few things that you will probably want to change in the runtime. We will look at the simple things in this tutorial, a subsequent tutorial will explore how to add things like iAds and Game Centre support.
   
  Figure 1. Changing your Icon & Launch Images in Xcode.
    
13.2.1 App Icons and Launch Images
      
The runtime comes with some default icons and launch images. The easiest way to replace these with your own is to use Xcode.
     
  1. Select the Project Navigator (top left button in the tool bar) and click on the top most item in the left pane, called Codea Template.
  2. If you then select the summary tab in the right hand (or middle pane depending on how you have Xcode configured) you should see something like Figure 1.
  3. Right click (control click) on any of these images and chose "Select File" to change them to your custom versions.
  4. There is a plethora of app icon and launch image sizes required, but you can get away with just having these six plus the App store image (which we will get to shortly). The iOS Custom Icon and Image Creation Guidelines lists exactly what dimensions are required and the naming conventions for these images.
           
13.2.2 Hiding the Status Bar
        
Note that you should take into account whether you will be showing the status bar when creating your launch images. Xcode will warn you if the dimensions of your selected images are incorrect. You can hide the status bar by setting the "Status bar is initially hidden" to YES in the info.plist file for your App (found in classes -> Supporting Files).
      
Figure 2. iOS Dev Centre Web Site.
          

13.3 The iOS Dev Centre

            
13.3.1 Provisioning Portal
      
For this next step we are assuming that you already have set up a paid developer account with Apple. The good news is that the App provisioning and certification process has gotten much easier than it was, but it is still a bit tricky so we will step you through the correct order in which things need to happen.
       
Figure 3. iOS Provisioning Portal.
                
  1. Open up you favourite browser and go the iOS Dev Centre site (Figure 2). Log in using the Apple ID associated with your Developer Account.
  2. Once you are logged in, at the top right of the iOS Dev Centre page is a set of links grouped as "iOS Developer Program". Click on the link which says iOS Provisioning Profile.
  3. You should already have a development and distribution certificate. If you haven't, the easiest way to do this is to use the Development Provisioning Assistant. You can start this off by clicking on the button which says "Launch Assistant", it is located in the middle bottom of the page (Figure 3).
  4. After you are certified we need to create a new App ID for our App. In the left hand pane of the iOS Provisioning Profile page, click on the link called "App IDs". On the App ID page you will be able to read more than you ever wanted to know about the care and feeding of App ID's. You will also be able to see the status of any App ID's that you currently have in place. Before your eyes glaze over there is one important paragraph buried in there. It starts with "The Bundle Identifier portion of an App ID can be substituted with a wild-card character (asterisk '*') so that a single App ID may be used to build and install multiple applications." We suggest that you don't do this, as wild-card App IDs cannot be used with Push Notifications or for In-App Purchase. 
  5. Click on the "New App ID" button in the top right of the screen, and this will take you to the Create a New App ID page shown in Figure 4. Here you have to answer just three questions but the first time you see this, it can be a bit confusing as to what to do. 
  6. For description we used "MinesweeperAppID". The description is not important, it is just to remind you which App this ID is for. The next question is important. It is to set the "Bundle Seed ID (App ID Prefix)". We suggest using the default "Use Team ID" as the prefix. As mentioned previously don't use a wildcard "*" for the prefix. The last question is used to set the "Bundle Identifier (App ID Suffix)". This needs to be unique for every App and the usual practice is to use a reverse domain name string. In our case we used "au.com.reefwing.Minesweeper". So what if you don't have a domain? It doesn't matter you just need to use something unique - you could perhaps base it on your name (e.g. "davidsuch.YourAppName"). Click on submit and you will be taken back to the previous App ID status screen where you should now be able to see your shiny new App ID.
  7. The last step in this stage is creating our Provisioning Distribution Profile. In the left hand navigation pane click on the "Provisioning" link and then on the Distribution tab. This will show a list of existing Distribution Profiles. Click on the "New Profile" button in the top right. Fill in the details. Distribution method is "App Store", choose an appropriate profile name (we used Minesweeper Distribution Profile), and select the App ID that you just created. Click on "Submit" and you are done.
  8. In the top right you will see a link which says "Go to iOS Dev Centre". Click on that and we will be ready for the next stage.
                
Figure 4. Creating a New App ID.
               
13.3.2 iTunes Connect
             
Figure 5. ITunes Connect.
             
Back at the iOS Dev Centre we now want to prepare our App for upload to Apple for review. We do this by using the link below the Provisioning Portal called iTunes Connect. Click on this now. You will probably be asked to sign in again at this stage. 
            
  1. On the iTunes Connect page (Figure 5) you will see a link to "Manage Your Applications" at the top of the right hand column. Click on this and then click on the "Add new App" button (top left).
  2. You will be asked to select your App type (iOS or Mac OS X). Click on iOS.
  3. Enter your App information. This is pretty self explanatory. For SKU we usually use the date (SKU = stock keeping unit, businesses use them to identify a unique product) and make sure that for Bundle ID you select the App ID created in section 13.3.1 above. The App name that you select will also need to be unique - in our case Minesweeper was taken so we went with iMinesweeper instead. When done click "Continue".
  4. Next select the availability date and price tier. Use the current (default) date if you want your App released as soon as it is approved by Apple. Select some future date if you want to control the release date. This can be handy if you are co-ordinating a massive marketing effort to drive up demand for your App and its first day sales. Selecting anything else but FREE for the price will bring up a matrix showing the price for that tier in different countries. Click "Continue".
  5. Fill out the version information and the age rating survey to determine its rating in the App store (e.g. Minesweeper comes out at a 4+ rating, the lowest possible). Clicking Frequent/Intense for some of these questions will mean that your App can't be sold in selected countries or in some instances at all. Next fill out your App's Metadata, this information will appear in the iTunes App store. The keywords are important because this is how customers will discover your App using the search functionality in iTunes. You are probably okay to go with the standard End User Licence Agreement (EULA), so the last step is to upload the images displayed in the App Store. The large App Icon needs to be 1024x1024 pixels in size. For the iPad screenshots, the easiest way to get these is using Organiser in Xcode (select your iPad from the left hand navigation panel and then screenshots. Run the App on your iPad using Xcode and then click the new screenshot button to take the images you want. You can then export these to a handy folder for upload to iTunes Connect). You can have up to 5 screenshots, drag and drop to change the order. Click "Save" when you are done.
  6. After saving your App data you will be brought to the App summary screen. Check that all the details are correct. The status at this stage should be a yellow "Prepare for Upload". Click the "View Details" button below your App icon, then in the top right hand corner, click on "Ready to upload binary".
  7. Answer the question about cryptography then click "Save" and then "Continue". Your App status will now be a yellow "Waiting for Upload". Click on App Summary and Done and you should see something like Figure 6, and we need to head back to Xcode for the next step.
            
Figure 6. iTunes Connect - Manage Your Apps.
       
13.3.3 Uploading Your Binary
         
In Xcode, we need to associate our App with the bundle ID that we set up in iTunes Connect. 

  1. Before proceeding, we need to download the distribution provisioning profile. In the Organiser window, click on Devices and then Provisioning Profiles in the left hand navigation pane. Click on the Refresh button (bottom left corner) and your new profile will be downloaded.
  2. Select the Project Navigator (top left button in the tool bar) and click on the top most item in the left pane, called Codea Template.
  3. If you then select the summary tab in the right hand (or middle pane depending on how you have Xcode configured) you should see something like Figure 1. Scroll up to the top of the Summary tab. The Bundle Identifier will currently have: com.twolivesleft.Minesweeper. This needs to be changed to the bundle ID that we established in the steps above. In our case we changed it to au.com.reefwing.Minesweeper. Check that the correct version number is listed while you are here.
  4. While we are here we will sign our code with the appropriate distribution profile. Select the "Build Settings" tab and scroll down to the Code Signing section. Under Code Signing Identity -> Release -> Any iOS SDK, select the distribution profile that you just downloaded.
  5. Before uploading we need to recompile the binary with all this good stuff included. Select Product -> Archive from the menu bar. After compiling you should see Archive Succeeded in Xcode and the Organiser window will automatically be presented showing your App Archive (Figure 7).
  6. In Archives (Figure 7), click on the Validate button (top right) and your archive will be validated prior to upload to Apple. At this stage, you may get an error - "No identities are available for signing." If you do, choose the Connect to iOS Dev Centre, "Download Identities" button. You should now be validated, click on "Finish"
  7. Click on Distribute, select submit to the iOS App Store, click "Next" three times and you will see a message "Your application is being uploaded".
  8. If all goes well you will get a "Submission Succeeded" message (Figure 8).
          

  Figure 7. Your App Archive in the Organiser Window.
    
Well done if you made it to this point. Believe it or not, Apple have actually streamlined and automated a number of steps in this process which used to be much more cryptic (especially for your first attempt at it).
  
If you want, you can go back into iTunes connect and validate that your App status has changed to orange and "Waiting for Review". In fact, we would recommend that you do this. There have been instances where people have uploaded their binary but for some reason it never moves on to "Waiting for Review." If this happens you can try rejecting the binary and re-uploading it. It will take about a week for the App to work its way up the review queue. Watch this space for updates...
     


Figure 8. Success! You App has been submitted for Review.

Saturday, August 4, 2012

Tutorial 12 - Submitting to the App Store Part 1

Webcomic Courtesy of Ethanol & Entropy

12.1 The App Store Journey


For many people the whole point of writing applications is to see them published in the App store and available for download from iTunes. Before you quit your job and go out and buy matching Porsche 911's you would be wise to get a few months of sales data under your belt. Like most endeavours, there is a bell curve of App sales. Everyone hears about Angry Birds developers making $70m, but there is a lot less media coverage at the other end of the bell curve. 

In a recent survey of more than 1,500 developers in 83 countries, it was found that the average per-app revenue is roughly $1,200 to $3,900 depending on the platform. Additionally, the survey noted that an app has roughly a 35% chance of generating between $1 to $500. This obviously means that most developers cannot rely on app development as their main source of income. However, it does mean that if you put the effort in you can make enough to fund your development habit. 

Our own experience is that you can never tell which Apps are going to be regular sellers (LifeGoals) and which will sink like a stone (LifeMovie). The Reefwing stable of Apps currently nets us around AUD$10k per annum, which is sufficient to purchase a MacBook Air, a new iPad, external development costs (Apple Developers Licence, App Sales Analytics, web-site and forum costs, etc.) plus a bit of change for the highly caffeinated beverages which programmers run on. We only work on this the odd night and weekend so with more application we imagine the rewards would be better. The thing that we are no where near recovering is the time spent developing. The average App takes us about 3 months from start to finish and while the proceeds roll in for some years to come, it isn't really passive income because sales quickly decline if you aren't frequently updating your App. 

However, lets face it - we would code if we didn't get paid anything so anything we do get is a very pleasant upside. There is also something addictive about tracking the daily "sales" of you App (even if it is free).

The other thing that most developers don't realise, is that the Apps which are successful in the App store, have as much time and money spent on marketing their Apps as they do on developing them. There is the odd exception but these are an exemption. Books have been written on this subject and we will provide our thoughts on the best approaches to marketing in a later tutorial.

But for now, let's have a look at how we go about getting our Minesweeper game submitted for approval.


Figure 1. Xcode in the Mac App Store.


12.2 What do I need and how much will it cost?


The process of getting your App approved is fairly straight forward but there is a fair bit of assumed knowledge which we will attempt to clarify. Sometimes we may miss a step due to our familiarity with the process and software, so don't hesitate to drop us a comment if you get stuck. This will help not only yourself but future readers.

To get your App in iTunes there is a bit of an investment. Presumably if you are reading this you already have an iPad and Codea, so we will assume that they are a sunk cost. All of the costs below are in Aussie Dollars unless stated otherwise. In addition to Codea on your iPad, you are going to need:

  • Some variety of Mac which will run Xcode (there are virtual machine solutions for those who want to do it the hard way or save money (e.g. for Windows or the Mac In the Cloud solution), but that is outside the scope of this tutorial). Any recent Mac will do the job so the cheapest new solution at the time of writing would be a Mac mini from $699 if you already have a monitor and keyboard.
  • A paid App Developer Licence. These come in a variety of flavours but the cheapest will cost you $99 per year. We have a company licence for tax reasons but individual is fine (and simpler to apply for). There is a bit more effort required if you want to sell apps (as opposed to making them free) but it doesn't cost any more, apart from the 30% cut of every sale that Apple keeps. You can register for free developer licence but this doesn't allow you to upload an App on iTunes. This process used to take a bit of time so apply before you need the licence. 
  • A copy of the Apple Xcode 4 Integrated Developer Environment (IDE), which is available as a free download on the Mac App Store (that also includes the OS X. and iOS  Software Development Kits - see Figure 1) to registered members of Apple’s iOS and Mac Developer Programs. This tutorial is based on version 4.4 of Xcode which runs on the Lion and Mountain Lion variants of OS X.
  • A copy of iExplorer from Macroplant so that you can extract your Codea project from your iPad and load it into Xcode. This costs $31.04 (US$31.49). We are using version 3.0.1.2 for this tutorial. There is also a free program for linux users called libimobiledevice which I understand comes in Windows and OS X variants but we haven't used it (thanks to Andrew Stacey for pointing it out). Another FREE option is iFunBox (thanks to Keebo for this suggestion).
  • The Codea Runtime Library - Which we will discuss in some detail in the next section. It is available free, courtesy of Two Lives Left. Version 1.4.3 was the version we used for the tutorial, it appears to still be a Beta version but works fine apart from some warnings when you compile.
  • And finally an internet connection is required, so that you can upload your App to iTunes Connect.

12.3 Step 1 - Download and Extract the Codea Runtime

    
[UPDATE: An assumption here is that you have already developed your App in Codea and it is operating without any obvious run time bugs. Don't bother submitting buggy code to Apple it will just be rejected and if by some chance it gets through the approval process, you will get a reputation for developing poor quality software. 

One of the issues with the App store process is that if you delete an App from your device it prompts you to rate it and provide a comment. Obviously, if a user is deleting an App it is likely that they are not going to rate it very highly. Since most happy users of you App wont bother to rate it (unless asked to), this can lead to a negative bias in ratings and comments which will dramatically effect your downloads and sales. 

To offset this bias it is good practise to prompt your users to rate and comment on your App just after something positive has occurred (e.g. a level in a game was completed) or if they have been using the App for some period of time. Under these circumstances you are much more likely to get a positive review. Like most things, moderation is the key, badgering your users for positive reviews will likely produce the opposite effect to what you were intending.

IMPORTANT: The latest version of Codea (v1.4.3) supports dependencies. These are a great tool for re-using code but unfortunately the current runtime (also v1.4.3) doesn't know how to handle them. So don't use dependencies if you plan on submitting your code to the App store.]

In order to submit your App you first have to get it working in the simulator on your Mac. We will also use this opportunity to add a touch more polish. The native language of iOS is Objective C so getting your Lua Codea App to run in Xcode requires the Codea Runtime Library


Figure 2. Git repository of the Codea Runtime Library.

Clicking on any of the Codea Runtime Library links in this tutorial will take you to the Git repository for the code (Figure 2). From here you can read a short description of the library, the current version, licence information (Apache License v2.0), requirements and setup. Have a read of all of this and then click on the zip button in the top left of the page to download a zipped copy of the Library and a script (make_project.sh), to your Mac development machine. We use chrome as our browser and in this you can right click (control click) on the downloaded file and select "Show in Finder" to take you to the file. Whatever you are using, locate the downloaded zipped file which is probably in the Downloads folder (depending on your preferences) and called something like "TwoLivesLeft-Codea-Runtime-1.4.3-0-g1539e18.zip", and then double click on it to decompress the archive.

This will create a folder called "TwoLivesLeft-Codea-Runtime-1539e18" or similar which contains a Codea Template folder, a copy of the licence, the readme file and the make_project script. To save on typing in the next step we renamed the folder "TwoLivesLeft-Codea-Runtime-1539e18" to "Codea" - but this is optional.

The next step requires us to get our hacker hat on and use Terminal. This is where the setup instructions in the Codea Runtime library assume a bit of knowledge, but don't worry we will take it slowly.


12.4 Step 2 - Enter the Terminal


    
Terminal is a program included with all versions of Mac OS X. It is located in the Utilities folder within the Applications folder. When launched, it provides a command line interface to control the UNIX based operating system. The default UNIX shell in Mac OS X Panther (10.3) or later is called Bash.


Figure 3a. The Terminal Application.

Go ahead and launch Terminal, you will see a window like that shown in Figure 3a. You should be in the root directory at this point. Type "ls" (don't include the double quotes) and you will see a list of files and directories which are in the current directory. You need to navigate to the directory which contains the files you just downloaded and extracted. In our case we first change directories to Downloads by typing "cd Downloads", you should see the  Terminal prompt change to something equivalent to:

DS-MacBook-Air:Downloads dsuch$ 

Type "ls" again if you have forgotten what the extracted zip folder is called, we changed the name to "Codea" so that we could remember, thus at the prompt we now type "cd Codea". 

Okay you should now be where we need to be. Type "ls" to check, hopefully you see:

DS-MacBook-Air:Codea dsuch$ ls
CodeaTemplate README.md
LICENSE-Codea.txt make_project.sh
DS-MacBook-Air:Codea dsuch$ 

This next step will create an Xcode template for your Codea project with the same name as your App. At the command line prompt, type "./make_project.sh yourAppName" where "yourAppName" should be replaced with the name of your App. Don't miss the full stop "." at the start of the script, this means run a command script in the current shell.

Note: if you plan to release your game on the iOS App Store please do not use the word "Codea" in the title of your game. (You may, however, mention Codea in the description and keywords for your game. Or in the game itself.)

There will be a brief pause when you execute the script and then the command prompt will return. Do another "ls" to see the newly created Xcode folder. Remember our App is called Minesweeper so the results look like:

DS-MacBook-Air:Codea dsuch$ ./make_project.sh Minesweeper
DS-MacBook-Air:Codea dsuch$ ls
CodeaTemplate Minesweeper make_project.sh
LICENSE-Codea.txt README.md
DS-MacBook-Air:Codea dsuch$

Notice the new directory called Minesweeper? That's what we need. We won't go into the detail of the bash script used but those really interested can work it out themselves by looking at the list of bash commands and the contents of the script.
      
You can now close down Terminal (command w will close the window), but remember where your new Xcode folder is located.

Figure 3b. The custom Dropbox.spritepack folder on the iPad
 
[Update: If you use custom sprites in your project then you need to copy across your Dropbox.spritepack folder (using iExplorer it is in Apps -> Codea -> Documents - see Figure 3b) and place it in the SpritePacks folder in the project created by running the script. In our example, the destination folder is Minesweeper -> SpritePacks. You will see the other standard sprite packs in the same location. To save space you could delete the images you don't use in this App from the copy of your Dropbox.spritepack folder.

If you haven't used iExplorer before then read section 12.6 below to get it set up. To copy from your iPad to the Mac, navigate to the location of the Dropbox.spritepack folder and right click on it, then select "Export to Folder" from the pop up menu.]

The next bit is optional but we think it is good practise. All of our Xcode projects are kept in a directory imaginatively called "Xcode Projects". Locate your newly created Xcode folder (in Downloads\Codea: for us) using Finder and copy or drag across to the directory where you will store your projects (Figure 4). 

Figure 4. Codea Runtime Xcode Template in Finder

In Figure 4. you will see a file in the Minesweeper directory called CodeaTemplate.xcodeproj, you can double click on this to load the project into Xcode, or follow the instructions in the next step.


12.5 Step 3 - Opening up the Codea template in Xcode


Stage 1 is almost complete. Open up the Xcode App, click on file, open in the menu bar and navigate to your new Xcode directory described in the previous section. Single click on the directory name and then click on the open button in the bottom right of the open file dialog. This will load the CodeaTemplate project into Xcode. 

[UPDATE: DO NOT run and compile the default runtime until your project is loaded and has replaced the Dungeon Roller project (see the next section). When the runtime is executed it copies the Lua files from the Project.codea folder into the iPad's document folder for this App. If you do this with the default folder it will copy across all the Dungeon Roller files and leave them there. At worst you may have Lua files with the same name which will cause very odd behaviour and will probably cause the App to crash. At best you are taking up unnecessary space on your iPad.]

If you do want to just see the default runtime project in operation, then in the top left of the Xcode screen you will see a play button, click on that to compile and run the loaded project code (Figure 5). As the project compiles you may see a bunch of warnings, don't worry about those. Eventually the iPad simulator will launch with the default Codea App "Dungeon Roller", one of the example Apps provided with Codea.



Figure 5. Xcode 4 and the iPad Simulator.

It is all very well to have an operating Codea Template project, but how do we inject our App so that it is playing in the simulator not "Dungeon Roller"? This is where iExplorer comes into play. Leave Xcode open as you do the next step.


12.6 Step 4 - Extracting your Codea project from the iPad


Connect your development iPad to your Mac using the USB cable and then launch iExplorer. All going well, iExplorer should look like Figure 6.


Figure 6. iExplorer connected to iPad

Using the left hand pane, navigate to Apps -> Codea -> Documents (Figure 7) and find your App folder (Minesweeper.codea in our case), right click (control click) on this and select "Export to Folder" from the pop up menu. It doesn't matter too much where you save this folder, we put it in Downloads.


Figure 7. Find your App in iExplorer and Export it to your Mac.

Back in Xcode, open up the classes folder using the left hand navigation panel (if you can't see the folders and files then click on "show the project navigator button" in the top left hand corner - it looks like a grey folder). Delete the existing Project.codea folder by right clicking (control click) on it and choosing delete from the pop up menu, select "Move to Trash" in the subsequent dialog box.

Open up Finder on your Mac, locate the yourAppName.codea directory and rename it "Project.codea". Drag your Project.codea folder into Xcode (just below the classes folder) and when you release the mouse button you will see Figure 8.


Figure 8. Import your Project.codea directory into Xcode


Check the "Copy items into destination folder's group (if needed)", Select "Create folder references for any added folders" and make sure your app's target is selected, then Click Finish.
 
You should now be able to compile and run your application in the Xcode iPad simulator. 
   
[Update: An alternative approach to that described in the Codea runtime (which we have described above) would be to: 
 
  1. Close Xcode.
  2. In iExplorer navigate to your Apps folder within Codea (e.g. Apps -> Codea -> Documents -> Minesweeper.codea).
  3. Right click on this folder and select "Export to Folder"
  4. Navigate into the folder created by step 2 (section 12.4). In our case it is called Minesweeper. Within this folder you will see a folder called CodeaTemplate.
  5. Within CodeaTemplate you will see the Project.codea folder. Export your project file (e.g. Minesweeper.codea) into this location.
  6. Right click on the default Project.codea folder and select "Move to Trash" from the popup menu.
  7. Rename your file to Project.codea
  8. Open Xcode and from the Menu -> File -> Open: select CodeaTemplate.xcodeproj from the folder created in step 2. ]