Archive for 2009

iPhone Development Tutorial

App Store Piracy: Worse than you think.

Two weeks ago, a minor update to Layers hit the App Store. The update included several important bug fixes and a few features, but one of the most major changes was the addition of a piracy tracking system. Each time the app is used on a jailbroken device, it phones home with a few (anonymized) metrics so that I can track the spread of pirated copies. Software on the Layers server gathers the data and prints out some cool statistics.

Technically cool, that is. Not really “cool” at all. I’ve sold around 1,500 copies of Layers this week and in the same 7 day period, more than 1,780 copies have been pirated. It’s flattering, to some extent; people obviously enjoy the app. However, it’s also evidence to a much larger problem that I feel Apple continues to overlook. The DRM used in iPhone apps hasn’t been changed in ages, and an app on a jailbroken device can be automatically cracked using another iPhone app in a matter of seconds. No command line tools. No hand-editing files. You double click the app’s icon and it cracks it. Done.

For “expensive” apps like Layers, piracy is an especially significant problem. The latest version of Layers runs about 22,000 lines of code, and my community and target market are small. Everyone needs to chip in so I can recoup the cost of development and rationalize extra time spent improving the app. The App Store’s layout and “Top 100″ formatting encourage 99¢ apps with limited utility, so it’s difficult to market a $4.99 drawing app to begin with. (I’ve been lucky enough to be a Staff Favorite on the App Store) Piracy rates above 100% really don’t help.

So what do you do? I feel it’s absolutely necessary to weed out the pirates. I wouldn’t mind providing illegitimate users with a time-limited or feature-limited version of the app. The problem is, current methods of screening for pirated copies are binary-dependent and patchable. In about a week, Layers will start displaying notices to pirates asking them to upgrade their “demo” copies of the app to a full version or “buy me a beer.” I hope that a few people will appreciate the app enough after using the pirated copy to consider paying. Even a 5% pirated-to-paid conversion rate would be an extra 15 sales a day.

In the future, I’d like to see Apple implement a secure model for confirming that users are licensed to use an app. A secure receipts model is built in to the In-App Purchase system, and I don’t see why it wouldn’t work for the app as a whole. The app would establish a secure connection to an iTunes server, exchange product identifiers and account details, and verify that a product had in fact been purchased. I don’t think Apple will implement anything in the near future, because it would require admitting that piracy was, in fact, an issue. We can dream, though.

A few other developers I’ve talked to have suggested creating a repository of device identifiers that have been nabbed during phone-home routines. It seems like a good idea, but I understand there’s some hesitation to start calling people pirates left and right. Apps would need to pre-emptively contact the repository, and a simple change to the UNIX hosts file could break the system.

So for now, It looks like I’ll be dreaming of an extra 1,700 sales a week.

4 1/2 stars! But you can’t compete with sex…

Layers finally dropped off the list of top paid entertainment apps on the App Store this week. It’s not all that surprising – for such an expensive app, I was happy to see it on there at all! I think this screenshot pretty much sums up my feelings, though. Of the top 100 entertainment apps, 13 of them are some variant of “hot babe” apps. Looks like you just can’t compete with sex.

Silly Story Maker

Last spring, I worked with Demetri Miller to create Silly Story Maker, an adaptation of an educational, sentence making soundboard for the iPad. With beautiful graphics and multiple voices to choose from, Silly Story Maker allows you to create simple sentences by combining thirty basic words and phrases.

Since the app is designed for kids, we wanted it to be highly responsive. The characters bounce as the app speaks their names and the entire interface is colorful, tactile and interactive. Demetri and I built the entire app using Apple’s standard audio APIs and Core Animation, which made this interactivity easy.

A few weeks after it’s release, Silly Story Maker was the #2 education app in Australia!

EXIF Orientation Flags and the iPhone Camera

Layers just came out this past Monday, and it has this great feature that allows you to add a layer to a drawing from your iPhone’s photo library. Simple enough – right? Apple provides the UIImagePicker API, we call a couple functions and get an image back. For most purposes, that would work great! Write some code, test, commit, done. The problem is, the picker interface allows the user to adjust the scale/positioning of the image, and the cropped image is always returned at 320x320px (or less)…

Mac OS X Stack Overflow Status Item!

I’ve become a huge fan of Stack Overflow over the last few weeks. The community there is helpful and fast and there are quite a few questions about Cocoa and Objective-C! It’s gotten to the point where I visit SO whenever my code is compiling – so I thought it was time to take matters into my own hands and make things easier to follow.

I’ve made a Stack Overflow status item for Mac OS X (also a “menu bar item” or a “system icon”) that shows your reputation and lists questions on the front page containing your interesting tags:

SO Status Item in Action

It’s pretty primitive at this point – you can click a question to view it, or click the tiny arrow to go to your user page. It updates every 90 seconds using the RSS and ATOM feeds from the site, so the most active questions are always available at a glance. It’s compatible with Mac OS X 10.5 and 10.6 – so download it and give it a shot! I know there are a lot of things that could be added – so leave a comment and let me know what you think.

Download the Stack Overflow Status Item for Mac OS X (0.5 MB)

PackBits algorithm in Objective-C

The PackBits algorithm is one of the TIFF data compression methods, and it’s also used for pixel data in Photoshop PSD and TGA files. It was originally developed for MacPaint, and although it’s still widely used, there isn’t a whole lot of information online about it. I spent some time this weekend writing a category to extend the NSData class and support the packBits algorithm, and I think I’ve finally got it.

PackBits is really dirt simple. If you have a string of hex values like 00 00 00 FF FF FF FF, it replaces series of  3 or more identical bytes with a count, and then the repeated byte. The input above would be 03 00 04 FF. A prefix is also attached to series of different bytes so the decoder knows how many bytes to pass through before looking for another header byte.

The full documentation of PackBits can be found on Wikipedia. My implementation is a modified version of the one available here: (source link at very bottom of page). That implementation is a modification of the official PackBits algorithm that allows slightly larger runs of data to be encoded in a single header + byte pair. I was interested in the original implementation only (since data written from any customized encoder could not be opened by a standard decoder) so I changed it back to the standard algorithm.

The primary function provided in the PackBitsAdditions category below is:

[objc] – (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip[/objc]

This function returns the packBits representation of the data in “range”, advancing “skip” bytes with each read. For instance, to read and encode every byte in “range”, you would provide skip = 1. To read and encode only every 4th byte, you would pass skip = 4. This may seem like an odd implementation, but it’s very handy when you need to encode the channels of an RGBA image separately (as in PSD format).

The other function in the category is packedBitsDescription. It describes the packed bits and the process that would be followed to decode them. This function could be easily extended to actually decode the data.

If you find this code useful, please leave a comment! I debugged this for quite a while, and I’d be happy to help if you run into any issues with my implementation!



@interface NSData (PackBitsAdditions)

- (NSString*)packedBitsDescription;
- (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip;



@implementation NSData (PackBitsAdditions)

- (NSString*)packedBitsDescription
NSMutableString * description = [NSMutableString string];
char * row = (char*)[self bytes];
int pbOffset = 0;
int pbResultBytes = 0;

while (pbOffset < [self length]){
int headerByte = (int)row[pbOffset];
if (headerByte < 0){
int repeatTimes = 1-headerByte;
UInt8 repeatByte = (UInt8)row[pbOffset+1];
[description appendFormat: @"Printing %u %d times. ", repeatByte, repeatTimes];

pbResultBytes += repeatTimes;
pbOffset += 2;
} else if (headerByte >= 0){
[description appendFormat: @"Printing %d literal bytes. ", headerByte + 1];
pbResultBytes += headerByte + 1;
pbOffset += 2 + headerByte;

[description appendFormat: @"Total: %d bytes decoded.", pbResultBytes];
return description;

- (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip
char * bytesIn = [self bytes];
int bytesLength = range.location + range.length;
int bytesOffset = range.location;
NSMutableData * dataOut = [NSMutableData data];

BOOL currIsEOF = NO;
unsigned char currChar; /* current character */
unsigned char charBuf[MAX_READ]; /* buffer of already read characters */
int count; /* number of characters in a run */

/* prime the read loop */
currChar = bytesIn[bytesOffset];
bytesOffset = bytesOffset + skip;
count = 0;

/* read input until there’s nothing left */
while (!currIsEOF)
charBuf[count] = (unsigned char)currChar;

if (count >= MIN_RUN){
int i;

/* check for run charBuf[count - 1] .. charBuf[count - MIN_RUN]*/
for (i = 2; i <= MIN_RUN; i++){
if (currChar != charBuf[count - i]){
/* no run */
i = 0;

if (i != 0){
/* we have a run write out buffer before run*/
int nextChar;

if (count > MIN_RUN){
/* block size – 1 followed by contents */
UInt8 a = count – MIN_RUN – 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf length:sizeof(unsigned char) * (count - MIN_RUN)];

/* determine run length (MIN_RUN so far) */
count = MIN_RUN;
while (true){
if (bytesOffset < bytesLength){
nextChar = bytesIn[bytesOffset];
bytesOffset += skip;
} else {
currIsEOF = YES;
nextChar = EOF;
if (nextChar != currChar) break;

if (count == MAX_RUN){
/* run is at max length */

/* write out encoded run length and run symbol */
UInt8 a = ((int)(1 – (int)(count)));
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&currChar length:sizeof(UInt8)];

if ((!currIsEOF) && (count != MAX_RUN)){
/* make run breaker start of next buffer */
charBuf[0] = nextChar;
count = 1;
} else {
/* file or max run ends in a run */
count = 0;

if (count == MAX_READ){
int i;

/* write out buffer */
UInt8 a = MAX_COPY – 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf[0] length:sizeof(unsigned char) * MAX_COPY];

/* start a new buffer */
count = MAX_READ – MAX_COPY;

/* copy excess to front of buffer */
for (i = 0; i < count; i++)
charBuf[i] = charBuf[MAX_COPY + i];

if (bytesOffset < bytesLength)
currChar = bytesIn[bytesOffset];
currIsEOF = YES;
bytesOffset += skip;

/* write out last buffer */
if (0 != count){
if (count <= MAX_COPY){
/* write out entire copy buffer */
UInt8 a = count – 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf length:sizeof(unsigned char) * count];
/* we read more than the maximum for a single copy buffer */
UInt8 a = MAX_COPY – 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf length:sizeof(unsigned char) * MAX_COPY];

/* write out remainder */
count -= MAX_COPY;
a = count – 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf[MAX_COPY] length:sizeof(unsigned char) * count];

return dataOut;


Custom compiler flags in XCode

So I’ve been messing with compiler flags in XCode for the last hour or so, and it turns out I was totally misunderstanding things. If you get info on a project or target in XCode, there’s a “User-Defined” section at the bottom that allows you to create your own flags for use at compile time. However, these flags are not actually passed into GCC! (Mistake 1!) I assumed that adding a key-value pair to the list would pass the flag straight through to GCC, but it appears that they are for use in build scripts, etc…

To pass a custom flag through to GCC so that you can use it in #ifdef and #if macros at compile time, you have to add a User-Defined Setting called “OTHER_CFLAGS”. For my project, I set the value to “-DIS_PHOTO_CHAT=1″. At compile time, the exact text is passed as an argument to GCC. You can set different values in different targets – and I was able to conditionally include some code in a header file using #if (IS_PHOTO_CHAT==1)…

It seems like you can use XCode’s built-in flags like ${TARGET_NAME} and ${PRODUCT_NAME} to insert variables into the value of OTHER_CFLAGS, but if your target name has spaces, I think you’re at a loss. I tried to set -DTARGET_NAME=${TARGET_NAME} for about an hour, but the target name had a space and I can’t get GCC to accept the value (tried quotes… no luck…) I’m no command-line-compiler-whiz, so I’m sure there’s a trick, but Google hasn’t turned anything up.

I’m still surprised OTHER_CFLAGS wasn’t preset to “” in the target build settings. There’s an empty field for “Other Code Signing Flags” (which seems less useful!) Oh well… Guess XCode is in permanent beta anyway?