Archive for the ‘ Development ’ Category

Answering an Often Asked Question

RA New Year 2013First, Happy New Year! I hope that 2013 proves to be a year of great growth and accomplishment for you and your company. Though I’ve been here for a short time, that’s what I’m looking forward to at Recursive Awesome.

As we continue to grow…that’s right…continue, I want to answer the question I’m most asked about Recursive Awesome: “Weren’t you guys bought by Code 42?” If it’s not those words exactly, it’s something close. And it’s a fair question. Especially based on coverage of the agreement with our friends at Code 42.

So let me answer it….

In short, during 2011, Recursive Awesome merged our engineering team with Code 42 Software to focus on building products based on Code 42′s cloud infrastructure. The professional services team continues to operate separately under the Recursive Awesome brand. It’s that simple.
We haven’t gone anywhere, we continue to work with great companies and brands on great mobile and web products…especially mobile. The people who founded Recursive Awesome still see to it that the dedication to innovation, quality, and customer service on which they founded the company continues to be its backbone. In short, we continue to strive for ‘awesome’.

In fact, that dedication to awesome has allowed us to grow our portfolio.* In 2013, we look forward to continue that growth, keeping in mind that we are not looking to be the biggest, just the best.

So if we can help make your 2013 ‘awesome’, we’re here, as we have been since 2009.

*We are looking for developer and software architects to join us. Please be sure to check our Careers page for opportunities.

 

Objective-C simple type comparison chart

I’ve always been a fan of PHP’s type comparison tables, and today Aaron and I started talking about how you can write the following in objective-c, but not in java:

if ( myObject )

I started wonderring how this works. Is [myObject description] getting called behind the scenes here? (Spoiler: The answer is no.)

I built a quick project to figure out why this happens, and some of my results were surprising. Essentially, you should never write if ( myObject ), because it is probably not what you want. It’s basically always true unless you initialize your objects to nil. (I actually recall that auto-initialization of objects to nil was one of the new language features announced last week at WWDC.)

Here are my findings for the statement: if ( X )

nil false — Interestingly, this is defined like this:
#define nil NULL
NULL false — Defined as follows:
#define NULL ((void*)0)
MyObj *myObj; true — (In some brief googling, I couldn’t figure out whether this was random memory access, or just looking at the pointer itself.)
MyObj *myObj = nil; false
MyObj *myObj = [[[MyClass alloc] init] autorelease]; true
@"" true — This is just creating a new NSString
0 false
1 true
YES true — Definition: #define YES (BOOL)1
true true — Definition: #define true 1
TRUE true — Definition: #define TRUE 1

I learned something. I hope Aaron did too.

Implementing “Pull To Refresh” in your Android App

From the android-pulltorefresh repo, https://github.com/johannilsson/android-pulltorefresh

“Pull To Refresh” is a UI gesture made popular by the Twitter for Iphone app. It allows a user to refresh a list by pulling down and releasing from the top of the list. IOS developers have had library support for this feature for some time now. Over in Android-land, only the official Twitter app has managed to implement this gesture. Long-promised to be open-sourced, Twitter’s solution is still secret and Android developers have no official means to implement this increasingly demanded feature.

But thanks to Android’s open eco-system, we can build this into our Android app’s using the open-source android-pulltorefresh library developed by Johan Nilson. With thanks to the projects other contributors, his library is capable of producing a UI experience similar to the Twitter app, with support all the way back to 1.5.

The project provides a simple and sufficient example app to demonstrate the library use, but I needed something a bit more robust when I was implementing this in my application. So I thought I’d share my changes here, applying it to example application provided in the project.

Let’s start with a brief explanation of how this works. The android-pulltorefresh library provides a custom ListView that includes a special header. The list is initially displayed with the first item selected. This hides the header from view. The custom ListView responds to touch events so that when you pull down on the list, the header is displayed and handles displaying “pull” and “release” text and animation based on how far you are pulling down. Once its released, the header remains visible with the “loading” message until the view is told the refresh is complete, then it resets the header so its hidden once again.

Getting the basic functionality implemented is straight-forward. First, setup your layout and reference the custom ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <!--
    The PullToRefreshListView replaces a standard ListView widget.
    -->
    <com.markupartist.android.widget.PullToRefreshListView
        android:id="@+id/android:list"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        />
</LinearLayout>

Now in your ListActivity you need to do 2 things, respond to the refresh request and let the view know when you’re done.
To handle the refresh action the custom view notifies an OnRefreshListener that you can implement to handle your refresh operation.
In the code below you’ll see that it implements the onRefresh method of the listener and wisely executes the refresh on a background thread using an AsyncTask.

 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pull_to_refresh);
 
        // Set a listener to be invoked when the list should be refreshed.
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });
        ....

Once your refresh is complete, notify the view by calling its onRefreshComplete() method. In this example, we call this method on the UI thread once the task is completed.

private class GetDataTask extends AsyncTask {
 
        @Override
        protected Void doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                ;
            }
            return null;
        }
 
        @Override
        protected void onPostExecute() {
            mListItems.addFirst("Added after refresh...");
 
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();
 
            super.onPostExecute();
        }
    }

So that’s basically how the example app from the project is setup. It just initializes a list of Strings and then on every refresh adds a String to the beginning of the list. In a real application we’ll probably need to beef this up a bit.

First let’s take that Task to task and do some real work. In my situation I need to refresh the list by calling an external api and retrieving all the data to be displayed. In this case its actually more efficient just to rebuild the whole list rather than calculating deltas and prepending to the existing list. For this example, assume we have a List as a class-level field managed by a custom ArrayAdapter.
Here’s the first iteration, the list is re-initialized in the task’s onPreExecute() phase, and the work is moved into the doInBackground() method.

private class GetDataTask extends AsyncTask {
 
        @Override
        protected void onPreExecute() {
		mList = new ArrayList();
	}    
 
        @Override
        protected Void doInBackground(Void... params) {
            JSONArray results = api.getData();
            for (int i=0; i &lt; results.length(); i++) {
                ListData data = parseResult(results[i]);
                mList.add(data);
            }
            return null;
        }
 
        @Override
        protected void onPostExecute() {
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();
 
            super.onPostExecute();
        }
    }

Seems like that should work ok, but I ran into a problem with this approach. As the user pulls down on the list, the onRefresh() method is called triggering the task, which starts by clearing out the mList array. At the same time, it seems that because of the UI changes, the system appears to be taking some measurements which is causing the getView() method to be called on the adapter that is managing the list. Now because we’ve emptied out the list, the application can exhibit some unpredictable behavior.
Let’s solve this in the next iteration by loading a temporary list in the background, and switching the list once we’re done. We should also consider that its possible we have some error while retrieving the new data, so in that case let’s not refresh the existing list. At least the user will still see their existing data.
Ok, now the GetDataTask looks like this:

private class GetDataTask extends AsyncTask {
 
        private List localList;
 
        @Override
        protected void onPreExecute() {
	    localList = new ArrayList();
        }    
 
        @Override
        protected Void doInBackground(Void... params) {
 
            try{
                JSONArray results = api.getData();
                for (int i=0; i &lt; results.length(); i++) {
                    ListData data = parseResult(results[i]);
                    localList.add(data);
                }
            } catch (Exception ex){
                localList=null;
                Log.e(TAG,&quot;Exception during refresh:&quot;,ex);
            }
            return null;
        }
 
        @Override
        protected void onPostExecute() {
 
             if(localList != null &amp;&amp; !localList.empty()){
                 mList = localList;
                 mListAdapter.notifyDataSetChanged();
             }
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();
 
            super.onPostExecute();
        }
    }

Alright, that’s looking pretty good now. For completeness we really should handle the possibility of the task getting cancelled. This can happen when the user navigates away from the app and the task is killed before its completed. This will cause the onPostExecute() method to not be called and so the onRefreshComplete() method won’t be called. Depending on how the user navigates through the app, they could return to this activity without going through the complete onCreate() lifecycle, and you’ll end up with the screen still showing the “loading” progress message in the header. This is common when using tabs between multiple ListViews.
Also, the documented best practices for implementing an AsyncTask says that in long running background work you should periodically check if the task has been cancelled and try to gracefully quit your work and exit. So let’s get all of that in there.

private class GetDataTask extends AsyncTask {
 
        private List localList;
 
        @Override
        protected void onPreExecute() {
	    localList = new ArrayList();
        }    
 
        @Override
        protected Void doInBackground(Void... params) {
 
            try{
                JSONArray results = api.getData();
 
                // check if task was cancelled during long api call
                if(isCancelled(){
                  return null;
               }
                for (int i=0; i &lt; results.length(); i++) {
                    ListData data = parseResult(results[i]);
                    localList.add(data);
                }
            } catch (Exception ex){
                localList=null;
                Log.e(TAG,&quot;Exception during refresh:&quot;,ex);
            }
            return null;
        }
 
        @Override
        protected void onPostExecute() {
 
             if(localList != null &amp;&amp; !localList.empty()){
                 mList = localList;
                 mListAdapter.notifyDataSetChanged();
             }
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();
 
            super.onPostExecute();
        }
 
        @Override
        protected void onCancelled() {
             // reset the UI
             ((PullToRefreshListView) getListView()).onRefreshComplete();
        }
    }

Now that you have a solid refresh implementation you may want to tweak the design of the refresh header. In the sample application they are using the Android “Light” theme. This makes the text black and easy to read. But if you’re using the default “Dark” theme you’ll find the text very hard to see. Here’s a look at the text portion of the refresh header layout, you can see that it references an attribute for the textAppearance style.

        <TextView
            android:id="@+id/pull_to_refresh_text"
            android:text="@string/pull_to_refresh_tap_label"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textStyle="bold"
            android:paddingTop="5dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
        />

Let’s tweak the color of the text to make it readable in our application. To do that, we’ll create a theme that overrides the style used by the textAppearanceMedium attribute. We’ll override this with our own style, which will inherit from the Android TextAppearance.Medium style and override the textColor attribute. Got all that?

First, here’s what Android’s style declaration looks like:

<style name="TextAppearance.Medium">
        <item name="android:textSize">18sp</item>
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">?textColorPrimary</item>
</style>

Now here’s our theme and style declaration:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustomTheme" parent="android:Theme.NoTitleBar.Fullscreen">
    	<item name="android:textAppearanceMedium">@style/TextAppearance.Medium</item>
    </style>
 
    <style name="TextAppearance.Medium" parent="android:TextAppearance.Medium">
    	<item name="android:textColor">#FFCDC9C9</item>
    </style>
</resources>

And finally edit the Android Manifest in order to use the new theme:

<application android:name="MyApplication"
                     android:icon="@drawable/icon"
                     android:label="@string/app_name"
                     android:theme="@style/MyCustomTheme">
</application>

And that’s it, everything you you need to implement the pull to refresh gesture, handle the operation and customize the UI.

By the way, the android-pulltorefresh library is made available under the Apache License, V2.0. So you need to maintain any NOTICE files and copyright headers from the source. But you are free to redistribute in derivative works for commercial use.

Originally posted on Shared State

Creating a grid view in iOS

Creating a table in iOS is easy, but there are times when you need a grid instead of a simple table. I’ll walk you through the steps for making a grid. In this example, I want a table that has three cells per row. The final product will look like this:

GridTableViewCell

The core piece in your  grid is a custom UITableViewCell. Start off by making a new class derived from UITableViewCell. I called mine GridTableViewCell. I want my grid to have 3 cells per row, so my interface is going to look like this:

@interface GridTableViewCell : UITableViewCell {
	UIColor *lineColor;
	BOOL topCell;
	UILabel *cell1;
	UILabel *cell2;
	UILabel *cell3;
}
@property (nonatomic, retain) UIColor* lineColor;
@property (nonatomic) BOOL topCell;
@property (readonly) UILabel* cell1;
@property (readonly) UILabel* cell2;
@property (readonly) UILabel* cell3;
 
@end

The UILabels are created in initWithStyle and are sized to fit within each cell. lineColor is self-explanatory. topCell is a bit trickier. Our line drawing code (see below) draws the vertical lines and a horizontal line at the bottom of the cell. However, this leaves the top cell in the table without a line on top. To work around this, we add a flag to the cell to indicate whether the cell is the top cell. If it is, draw a line on the top of the cell.

We do our line drawing in drawRect. In the implementation for GridTableViewCell I have overridden the drawRect method and added the line drawing code. Here is what it looks like:

#define cell1Width 80
#define cell2Width 80
#define cellHeight 44
 
- (void)drawRect:(CGRect)rect
{
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextSetStrokeColorWithColor(context, lineColor.CGColor);       
 
	// CGContextSetLineWidth: The default line width is 1 unit. When stroked, the line straddles the path, with half of the total width on either side.
	// Therefore, a 1 pixel vertical line will not draw crisply unless it is offest by 0.5. This problem does not seem to affect horizontal lines.
	CGContextSetLineWidth(context, 1.0);
 
	// Add the vertical lines
	CGContextMoveToPoint(context, cell1Width+0.5, 0);
	CGContextAddLineToPoint(context, cell1Width+0.5, rect.size.height);
 
	CGContextMoveToPoint(context, cell1Width+cell2Width+0.5, 0);
	CGContextAddLineToPoint(context, cell1Width+cell2Width+0.5, rect.size.height);
 
	// Add bottom line
	CGContextMoveToPoint(context, 0, rect.size.height);
	CGContextAddLineToPoint(context, rect.size.width, rect.size.height-0.5);
 
	// If this is the topmost cell in the table, draw the line on top
	if (topCell)
	{
		CGContextMoveToPoint(context, 0, 0);
		CGContextAddLineToPoint(context, rect.size.width, 0);
	}
 
	// Draw the lines
	CGContextStrokePath(context);
}

The UILabels are created in the cell’s init function. The code to create the labels looks like this:

	cell1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell1Width, cellHeight)];
	cell1.textAlignment = UITextAlignmentCenter;
	cell1.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
	[self addSubview:cell1];

The final important task to handle in the cell is to redraw the cell when its topCell state changes. Since we are reusing cells in our table view, the cell does not always get redrawn and we can end up with an extra top line where there should not be one. The remedy to this problem is straightforward – override the setter function for the topCell property.

- (void)setTopCell:(BOOL)newTopCell
{
	topCell = newTopCell;
	[self setNeedsDisplay];
}

UITableView

Now that we have our custom table cell, let’s use it in our TableView. All the magic happens in cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
 
    GridTableViewCell *cell = (GridTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[GridTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.lineColor = [UIColor blackColor];
    }
 
    // Since we are drawing the lines ourself, we need to know which cell is the top cell in the table so that
    // we can draw the line on the top
    if (indexPath.row == 0)
        cell.topCell = YES;
    else
        cell.topCell = NO;
 
    // Configure the cell.
    cell.cell1.text = [NSString stringWithFormat:@"%i", indexPath.row];
    cell.cell2.text = [NSString stringWithFormat:@"%i", indexPath.row];
    cell.cell3.text = @"Sample text";
 
    return cell;
}

The final task is to turn off the table view’s default lines. This is done in viewDidLoad in our view controller:

- (void)viewDidLoad
{
	[super viewDidLoad];
	// Turn off the tableView's default lines because we are drawing them all ourself
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

Wrap-Up

That’s all there is to it for making a grid view. I have posted a demo project on GitHub – GridTableView.

Git Beginner Links

As a new Recursive Awesome employee, I’ve only been using Git regularly for a few weeks now. At previous jobs I’ve used SVN, and before that CVS, so I thought myself an old hat when it comes to source control, but Git has forced me to learn some new tricks. I have found the following resources to be extremely helpful in my transition to using Git exclusively:

  1. Git – SVN Crash Course – http://git.or.cz/course/svn.html – This tutorial on getting started with Git was written for people already familiar with SVN. It has side-by-side comparisons of Git and SVN commands, with explanations. Definitely very helpful.
  2. A Successful Git branching model – http://nvie.com/posts/a-successful-git-branching-model/ – This was actually not new to me here at RA, but because it was written for Git, I had basically read it once, and not referred to it again. Now that I am actually using Git, I have found myself referring to the examples in this article at least once or twice a week.
  3. git hub – http://github.com/ – git hub recently threw this cute and helpful graphic up at the top of my dashboard, basically letting me know that there are detailed tutorials for several common git tasks. Though I have needed help with git quite a bit these last weeks, I have managed to perform all these tasks without much help. Kudos definitely go to git hub for their excellent contextual help when you first sign up for the site, and when you create a new repository, or even just browsing other people’s repositories. Often this help text contains the actual git commands you need to run to perform these everyday tasks. For posterity, however, here are the (also excellent) help docs that git hub linked to in the graphic above:
  4. git ready – http://gitready.com/ – This site is a gem. There are basically just a bunch of articles about Git here. Many are task-specific howto-type articles, but just as many are just things you should know about Git in general. This is probably not the first resource you should turn to if you’re JUST starting out, but I’ve found more than one search for help has led me to one of these informative articles.
  5. It should go without saying, but one of the best resources is of course Git itself.
    % git --help

I am happy to report that learning to use Git has simultaneously been one of the most frustrating and one of the most enjoyable and rewarding aspects of starting out here at Recursive Awesome.

Six Tools For CSS3 Success

Browser updates often introduce new and exciting features that make browsing the web faster, more secure, and easier. These types of changes have typically have users doing fist pumps, but what about developers? Lately, we’ve been getting our fill of fist-pump worthy additions as well. Simple animations, fancy transitions, and dynamic drop shadows are all possible with CSS3. With the latest round of browser releases, many of these features are at a level of support where they are able to be used more widely. Keep in mind that not all users upgrade their browsers the instant an update is released. However, the older browsers will just ignore the features they doesn’t support.

Firefox 4 has been in beta for several months and is scheduled for a release in November. While it already supports some CSS3 in version 3.5, Firefox 4 brings in support for some of the more flashy features. IE9 was just unleashed last month. As is typical for Microsoft, IE9 supports CSS3 at a very rudimentary level, but any improvements over previous releases are welcome. Of course the Webkit-based Chrome and Safari have led the pack with their CSS3 support for quite a while and the latest versions continue to uphold this pace. Not to be forgotten are the mobile browsers; the most popular of which are based on Webkit. The browser landscape is still varied, but it’s at a point where we can start dropping in CSS3 features and know that most users will see them. Besides, do websites need to look exactly the same in every browser? I’ll give you a hint, the answer is no. If you’re looking to add that next level of polish to your design and you haven’t tried CSS3 yet, think about giving it a shot.

A number of very specific and some more generic tools have popped up online to help you craft the most widely compatible CSS3 possible.

Border Radius – Dynamically rounds corners of a box depending on the values entered. Handy for coming up with different radii on different corners or for rounding less than all 4 corners.
Mother Effing Text-Shadow – Drag the sliders to create a text shadow effect. Also allows you to change the color of the shadow using HSL values.
Ultimate CSS Gradient Generator – This tool allows you to generate CSS3 gradients and provides a familiar interface for Photoshop users.
CSS3 Please – The kitchen sink of CSS3 generator sites. Includes corners, shadows, gradients, transitions, animations, and fonts.
Selector Gadget – Javascript bookmarklet that gives CSS3 rules by selecting an element. OK, so this tool isn’t CSS3 specific, but it is handy nonetheless and does spit out complex CSS3 selectors.
CSS3.info Previews – CSS3 examples. Alright, this isn’t a tool either, but it comes in handy when you just want to see what a particular CSS3 feature looks like.

8 Super Super Useful Open Source Projects for iPhone

I’m always on the lookout for great plugins and libraries to use in development. Here are some projects we like @RecursiveAwesum.

json-framework

Any time you need to need to call a web service you’re going to be parsing JSON data. Add json-framework to the project and never, EVER, worry about parsing again. This project has been rock solid for over two years and I can’t recommend it enough. It extended cocoa classes nicely with categories which make working with NSString, NSArray, and NSDictionary a breeze.

json-framework

Zebra Crossing Bar Code Reader

Need bar code or QR code scanning in your app? Call the zebra.

Zebra Crossing Bar Code Reader

Appirater

Appirater is a great tool to ask your users to rate your app. It used to be a great way to foil the App Store’s negative rating bias. However, I’ve noticed you are no longer asked to rate an app when removing it from your phone in SDK 4.1, but this is still a great way to prompt your users.

Appirater

TDBadgedCell

This is a UITableViewCell subclass that adds a “badgeNumber” to a table cell. This badge draws in an identical manner to the badges present in MobileMail.app.

TDBadgedCell

MBProgressHUB

From the README – MBProgressHUD is an iPhone drop-in class that displays a translucent HUD with a progress indicator and some optional labels while work is being done in a background thread. The HUD is meant as a replacement for the undocumented, private UIKit UIProgressHUD with some additional features.

MBProgressHUB provides a very smooth user experience and will add a nice finish to your app.

MBProgressHUB

SyntesizeSingleton.h

If you want to use the Singleton Pattern in your app, Matt Gallagher from Cocoa With Love has a great example on how to do so with his SynthesizeSingleton.h.
SynthesizeSingleton.h

Twitter-OAuth-iPhone

Twitter-OAuth-iPhone

OAuthConsumerFramework

OAuthConsumerFramework

While the above are excellent projects you shouldn’t add them to your project without reviewing the code. Good developers don’t cargo cult code. Always know what you’re code is doing.

Wiping an S3 bucket clean

Photo by bkoger

Photo by bkoger

Amazon’s Simple Storage Service, or S3, is a wonderful resource for developers. For very little money, you can throw a ton of data out on Amazon’s servers and not have to think much about backing it up.

For an internal application we’re writing, we are using S3 to store photos; a pretty common use of S3. There is a script that connects to a remote server, asks for some data, and then saves the data in our database and pushes any images to S3.

In writing the script, several thousand files were pushed up to a test bucket in S3. As it turns out, buckets can only be deleted if they are empty and deletes can only be issued 1 at a time. So if you have a million objects out on S3, then you have to make, literally, a million and one requests to delete the bucket. Not easily done using your typical S3 GUI tools.

This is where a handy little Ruby script called s3nuke comes in. You pass it your keys and the buckets you want to clear out and it goes to town. The script makes heavy use of threading and will use up to 10 threads by default. More threads can be specified with a command line option.

./s3nuke -a 123ABC -s ABC123 bucket-to-be-emptied

The code is available on Github. http://github.com/SFEley/s3nuke

Note: The script is written with Ruby 1.9 in mind, so run it on 1.8 at your own risk.

Quick Tip: Sprinkle, passenger-stack, and Rails 3

If you’ve tried to get passenger-stack and Sprinkle 0.3.1 running recently, you might have run into the not-so-helpful error: uninitialized constant ActiveSupport::Dependencies (NameError).

It appears that if you have  one of the Rails 3 beta gems installed, then Sprinkle gets confused when trying to use ActiveSupport’s Dependencies module. This error can be fixed by modifying lib/sprinkle.rb in the gem directory. Add the following line right after require ‘activesupport’ (line 2):

require 'active_support/dependencies'

Hopefully the author of Sprinkle will get this bug fixed up soon. An issue on Github has been created.

Update: Github user ahaller has submitted a patch. It sounds like it’s OK to just add the require line even if you are on Rails 2.

Using Git to Manage iPhone Provisioning Profiles

Every iPhone developer with an app in the Apple App Store has dealt with the frustration of code signing. Try searching for “iphone code signing error” on Google and you get almost a million results. The purpose of code signing is to tie developers, apps, and devices together in a tangled web in an attempt to prove you are actually yourself, your iPhone is in fact yours, and Apple has authorized you to run or submit your app.

Sounds like fun right?

The way to sign your app is to associate it with a provisioning profile. Creating a provisioning profile is beyond the scope of this post, but you can find more information here. You’ll need a current iPhone developer account to access the docs. Sorry.

So what is this post about then? Well, once you have a few iPhone apps under your belt you’ll find that you have a ton of profiles to manage. Development profiles to test your apps on your device. Ad-hoc profiles to send out beta versions to your testers, and Distribution profiles for submitting your apps to the App Store. They all live in the same place on your Mac and will have non-human readable names if you’ve followed the Apple documentation and dragged and dropped them into Xcode. This makes it a bit tough to know what profile goes with which app.

What are provisioning profiles?

The docs define provisioning profiles as “… a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code.” Translated this means you have to have a development profile to run your app on your device or a distribution profile to have the app accepted into the app store.

How XCode/iTunes uses them

I’m not going to cover how to sign your apps in this post either. But, rather explain how XCode uses them and how to organize them. Both XCode and iTunes use profiles. XCode to sign the apps and iTunes to install them. Whether you’re signing or installing profiles they live in the same place. Fire up Terminal.app and issue the following commands to find your profiles.

$ cd ~/Library/MobileDevice/Provisioning Profiles/
$ ls

Profile Installation Methods: Drag & Drop vs. Finder

Most of the Apple documentation tells you to drag and drop a profile into XCode to install it. This works but your profile is renamed along the lines of “0ED00060-C42C-4E3F-932F-30F22F79A14C.mobileprovision”. Good luck on knowing what file is.

I prefer move the profiles manually in Finder to avoid the automatic renaming. I like to name my files project.type.date.mobileprovision or trickiwiki.adhoc.03352010.mobileprovision.

What is Git?

Unless you’ve been out of software development for a few years you’ve probably heard of git. Git is distributed version control system for source code and when coupled with a website like GitHub it makes contributing to open source project easy. One of the great things about git is the ease of branching.

For info on how to use and configure git please refer to Scott Chacon’s Pro Git book & website

Creating a Git Repository

Now that git installed we can finally get to the meat of this post. So fire up Terminal.app and issue the following commands. But first move all of your provisioning files out of ~/Library/MobileDevice/Provisioning Profiles/

$ cd ~/Library/MobileDevice/Provisioning Profiles/
$ git init
$ touch README
$ git add README
$ git commit -m 'first commit'

You have created your git repository and added a blank file named README to it.

Using Git Branches

You new git repo comes with a pre-made branch named master. For our purposes we’ll leave this one alone. Run the following command any time to see the branches in your repo.

$ git branch

I like to create a branch for each app. To create a new branch run…

$ git branch app_name1
$ git checkout app_name1

You’ve just created a new git branch for app_name and moved into it. Now save your profiles for app_name1 in cd ~/Library/MobileDevice/Provisioning Profiles/ and run

$ git add .
$ git commit -m "Profiles for app_name1"

Now your profiles are safely stored in your project branch. Now to make a new project branch we need to move back to the master branch and issues the commands to make a new branch. So run the following…

$ git checkout master
$ git branch app_name2
$ git checkout app_name2

Move the profiles for app_name2 into ~/Library/MobileDevice/Provisioning Profiles/ and commit them into git.

$ git add .
$ git commit -m "Profiles for app_name2"

Did you notice that ~/Library/MobileDevice/Provisioning Profiles/ was empty when you put the profiles for app_name2 in there? That’s because the profiles for app_name1 are tucked into the branch for app_name1. To switch between branches just use the git checkout command.

$ git checkout app_name1
$ ls
app_name1.mobileprovision
$ git checkout app_name2
$ ls
app_name2.mobileprovision

Are you starting to get the idea?

What Branch Am I On?

Now that we have all of these branches how do you tell which one you’re working with. As I said before the command git branch will show you the branches

$ git branch
app_name1
* app_name2

The * indicates the active branch. But typing git branch over and over is annoying so I use some shell scripts from Jon Maddox to always show me which branch I’m on.

[proton:Provisioning Profiles[trickiwiki]$

In the example above the branch is shown as “[trickiwiki]“. Pretty sweet, huh?

Git Checkout Usage with XCode/iTunes

The one thing you need to remember when using this system to manage your profiles is XCode and iTunes are not very smart. They only check for profiles on startup. So you need to remember to checkout the correct branch before opening those apps. This took some getting used to until I made it part of my workflow.