Free Status Orb Images for iOS Apps

I’m currently wrapping up development of my next app for Mac, iPhone and iPad.

One screen in this app uses green, red and gray status orb images to indicate the correctness of the user’s credentials for a particular online service.

For the OSX edition I was able to use the excellent NSImageNameStatusAvailable, NSImageNameStatusUnavailable and NSImageNameStatusNone status orbs that come pre-bundled with Cocoa and are intended for use with NSImage.

The iPhone and iPad editions of my app however could not avail themselves of these handy graphics and I had to create my own, which I now share with you for free.

I used Inkscape to create the below green, red and gray vectors (in SVG) from which I could export rasterized versions. The appearance is more or less keeping inline with the orbs in OSX but the files are originals.

Status orb green Status orb green 2x Status orb red Status orb red 2x Status orb gray Status orb gray 2x

The below file contains those SVG and PNG files in both Retina display and non-Retina display resolutions. Download File

Feel free to use/modify these in your iOS projects.

iOS UDID Officially Gone

Today Apple announced that as of May 1st 2013 iOS applications retrieving UDIDs (Unique Device IDs) will be rejected prior to distribution.

Previously the UIDevice class’ uniqueIdentifier method used to obtain the UDID had only been deprecated.

Apple now recommends developers to use the UIDevice class’ identifierForVendor method which is available from iOS 6.0.

The returned value is unique to the device for all apps developed by a given software vendor.

This should replace the UDID quite well, while also preventing multiple vendors from working together to track users across apps.

If your app must remain compatible with iOS 5 or earlier this method will not be available and the workaround, as I wrote in an earlier post, is to access the device’s network MAC address which is also unique to the device.

How to Make a Build Script for Bundling dylib Files into an OS X App

Although I’m not new to Mac development I never needed to embed a dynamic library (.dylib file) into an app until just recently. Needless to say I struggled with this for a while.
I also wasn’t able to locate any single, up to date and reputable tutorial on the topic so I wanted to collect the bits and pieces I found into this single, easy to understand article so I could help others.

The strategy that worked for me, and which I’ll cover below, was to create a post-build script.

 

Understanding Dynamic Libraries

Dynamic libraries have encoded within them a “name” which actually serves as a path by which they are located. In order for your already built app to reference a dynamic library it needs to know where to find it and during the build process this encoded name becomes that location. When your app starts up it attempts to load all its dependencies at their named paths and unless said dynamic library is installed on the user’s Mac the app will crash.

Of course you can never be 100% certain a user will have the dynamic library beforehand and installed at just the right location. It therefore makes more sense to bundle the library within your app.

Determining the Encoded Name

In your app’s main target create a post-build script and enter the commands below, replacing MyProject with the name of your project and the “ThirdParty/Abc/” with the path of the .dylib file relative to your project’s base path.

echo OTOOL BEGIN\n
otool -L MyProject/ThirdParty/Abc/Abc.dylib\n
echo OTOOL END

Now build your project and inspect the build log (Right click on any build issue and select the “Reveal in Log” menu item). The output from otool’s execution should appear below “OTOOL BEGIN” and above “OTOOL END”.

Did it work? Okay, now remove these 3 lines from your build script but keep the dynamic library’s name handy for the last step.

 

Overriding the Dynamic Library’s Encoded Name

The below command overrides the dynamic library’s name to one that will match its path within your app’s folder (remember an OS X app is really an .app folder, not a file). Typically libraries appear under the “Frameworks” folder. NOTE: Make sure you have a “Copy Files” build phase which will copy the file from its source to this “Frameworks” folder by specifying it as the Destination.

install_name_tool -id @executable_path/../Frameworks/Abc.dylib MyProject/ThirdParty/Abc/Abc.dylib

NOTE: The executable path variable is the folder in which the true binary executable is located. Typically in the PRODUCT_NAME/Contents/MacOS folder. So the path @executable_path/../Frameworks/ is really PRODUCT_NAME.app/Contents/Frameworks.

In the above command replace Abc.dylib with your dynamic library’s filename.
Also replace MyProject with the name of your project.
In this example the source folder for the Abc.dylib is under “ThirdParty/Abc” and you’ll need to provide an appropriate path to your dylib file, following your project’s conventions.

Now that the dynamic library’s new encoded name matches the new location in the “Frameworks” folder the next step is to tell your app to expect it there.

Remember this is a post build step. Your app was originally linked against the not yet renamed dynamic library and thinks it needs to look for it there still. This is where we use the encoded name otool reported to us…

 

Modifying the App’s Reference to the Dynamic Library

The below command changes the referred location of the dynamic library from its original path to its new one within the “Frameworks” folder.  Add it to the bottom of your script.

install_name_tool -change usr/lib/Abc.dylib @executable_path/../Frameworks/Abc.dylib MyProject/ThirdParty/Abc/Abc.dylib

As with the previous step, modify the paths to reflect those of your project and take special careful to type all paths accurately.  The above “usr/lib” path may differ from that of your dylib and this is why you used otool.  Take the path you discovered with that tool and if different from “usr/lib” replace it.

Run the build once more. If no errors occur and the dylib file is indeed bundled in the “Frameworks” folder (you can check by stripping the .app extension from the folder) there is one last thing to test. Running the app!


Run It

Archive the project (Xcode menu Product → Archive). This will open the Organizer window. From here you can press the Distribute button which will prompt you for the method of distribution.
Choose “Export as Application” and export it to your desktop. The app is now waiting for you there and you only need to double click it. If the app starts up without complaint you’ve successfully bundled the dynamic library!

If the app doesn’t execute, check the error report OS X offers in the crash dialog to see what file path it expected to use. You can also reuse the otool command shown in the first step at the bottom of your build script to double check that the dynamic library was indeed renamed.  Most errors end up being mistyped paths and otool can prove so.

How to Draw Thick 2D Lines in OpenGL

Background

In a recent project I needed to draw lines NSBezierPath style in OpenGL at different widths and which may be zoomed arbitrarily by the user. As OpenGL does not natively support rounded end caps on lines drawn with glVertex2f I employed the popular technique of drawing a GL_POINT at both ends of a line using the same vertices as the line itself.

This approach works to a point but, I discovered, not on every machine.

On my development iMac the OpenGL implementation handled this without complaint, but when testing it on a different machine (a Mac mini) I noticed an odd effect.  The points I was using to simulate end caps were gigantic in comparison to the lines themselves and it resembled a narrow bone with large joints on both ends.

I investigated the cause by querying the GL_SMOOTH_LINE_WIDTH_RANGE and GL_SMOOTH_POINT_SIZE_RANGE parameter values.  It seems the points could range from 1.0 – 64.0 in size but the lines only 1.0 – 7.0 on this test machine. What I needed was a width of 20.0.

At this point it was clear that I would need to replace my native OpenGL lines with quad based pseudo-lines. Searching online for an existing implementation yielded nothing that fit my needs so I ended up rolling my own, which I now offer for free to everybody via
my Github repository (JFOpenGLUtil.h, JFOpenGLUtil.m).


How It Works

The implementation is simple. A GL_QUAD is a 4-sided polygon consisting of 4 vertices and, if kept narrow, it can be made to resemble a line.  If we know the line width and the beginning and end points we’re ready. We only need to calculate one offset point from the beginning point.  This offset point is ½ the line width in a perpendicular angle from the line. Once this offset is determined it can be reused 4 times to render the quad.


How To Use It

Unlike glVertex2f, you’ll need to provide 2 points at once. This is because the angle (from the beginning to the end) is needed to determine the GL_QUAD vertices.  If you’re using a for loop to iterate over your points just skip the first point like this…

Point *previousPoint = nil;
for (Point *point in pointArray) {

	CGPoint endRenderPoint = [point renderPoint];

	if (previousPoint != nil) {
		CGPoint beginRenderPoint = [previousPoint renderPoint];

		[JFOpenGLUtil drawQuadLineWithWidth: lineWidth
					red: redColor
					green: greenColor
					blue: blueColor
					from: beginRenderPoint
					to: endRenderPoint];
	}
	previousPoint = point;
}

 

With this approach lines of virtually any width can be supported.  But don’t forget, anti-aliasing is needed to keep the quad line from looking jagged of course.  I hope this implementation helps you if OpenGL has been less than cooperative with your app’s line drawing.

Free Web Sharing Preference Pane Replacement For Mountain Lion

I previously wrote about how to restore your Sites folder that OS X 10.7 Lion no longer created by default.

Today I discovered, and spent many hours trying to overcome another snag introduced by OS X 10.8 Mountain Lion.  It would seem that the “Web Sharing” Systems Preference is now completely removed.  In the end I stumbled upon a replacement Systems Preference pane which, if anything, is easier to use than the one Apple originally offered.

http://clickontyler.com/blog/2012/02/web-sharing-mountain-lion/

 

New web sharing

There are no two ways about it, Apple is continuing to take actions to make OS X a more difficult OS upon which to develop websites.  Why I can only guess.  The automated approach Apple offered earlier eliminated any potential for errors which is exactly what I got myself into today by not properly creating the per-user Apache configuration extension file.  OS X is supposed to be the gentler Unix and this move is confusing.  At this rate I expect OS X 10.9 to not even have Apache installed.

Today’s saviors are the fine people at ClickOnTyler whose new preference pane brings back that one click automation.

iOS Icon Drop Shadow Tutorial

In the “About” screen of each of my apps I display the app’s icon with a nice drop shadow under it to give the icon that tangible feeling.

Icon with drop shadow

Today I thought I’d share the technique I use to achieve this effect.

In your project, add the QuartzCore framework to your main target. You’ll need this to help you reference your icon view’s layer property (CALayer) which is responsible for rendering the drop shadow.

Once you’ve done that add the shadow effects you see in my code below to your icon initialization logic…

iOS Icon Drop Shadow

Some items to note about the above sample:

  • The shadow color is a translucent black.
  • The shadow is 2 points lower than the icon and has a 2 point radius.
  • Clipping to bounds is turned off so the shadow is not clipped off.

I encourage you to experiment with these settings to find the right look for your icon or image.

Professional Layouts in OS X and iOS – Open Source View Position Utility

Introducing JFViewPositionUtil

I created JFViewPositionUtil for KEYBOX 2.0. I hand code my interfaces rather than use Interface Builder, and version 1.0 proved extremely difficult to lay out professionally while also balancing the consideration of localization.

Why would anybody in their right mind NOT use Interface Builder? Don’t get me wrong, it’s a fine tool but for the degree of customization I and many developers require it doesn’t quite cut it.

In the case of KEYBOX 1.0, a layout that would look good in English might make Japanese look awful. My initial approach to handle this was to adjust the font size on a per-language basis. It worked but was nowhere near optimal.

In version 2.0 I resolved to fix this and since its release I’ve used this class in all my products. It’s matured to the point where I believe it to be beneficial to others as well, and to this end I’ve decided to open source it.


Class Design

I designed this class to be goal oriented. That is, whatever your goal, you typically only need to invoke a single method offered by this class. It’s even a singleton so there is no need to instantiate it.

This utility class works with both OS X and iOS projects but it should be noted that it is designed to work in coordinate systems where the point of origin (0, 0) is the top left corner. In other words, you’ll want to flip your views in OS X projects when using this class.

Lazy-initialization of views

A quick note, since this utility class operates mainly on the notion of positioning views relative to others, it is beneficial to adopt a lazy-initialization approach to view creation. This way sibling views upon which your view depends will be initialized and positioned by the time you need to base your view’s position on them. All of the below examples in this post will use lazy-initialization of UIViews for iOS.


Common Layouts

The best way to demonstrate this class’ abilities is to simply show you. Since this class is goal oriented I’ll break things down by common layout goals.

■ Label to the right of an icon
This is a common layout pattern, and the code might look something like this…

Label right of icon

One variation of this is the case of a multiline label. You probably wouldn’t want to vertically center your label to the right of your icon. Instead, it might look more professional to snap the icon’s top right anchor point 5 points left of the label’s top left point. I’ll discuss this technique a bit later.

■ Center aligned titles/headers

Sounds simple enough right? The title is a label with a bold font. Here’s the code…
Centered Header

It’s generally a good idea to first call sizeToFit on labels prior to aligning them with JFViewPositionUtil, especially when you intend to center align them.

■ Text field under a label

Have a text field that should appear left aligned, say, 10 points under a label explaining its purpose? Here is how to accomplish this…

Left Aligned Textfield

And to right align it instead…
Right Aligned Textfield

This just touches upon some of the high-level functionality of this class.  Other useful methods exist, each aptly named for its purpose.

Going Beyond

If JFViewPositionUtil’s high levels actions don’t suffice its low-level anchoring system will. The code is based on anchoring points (shown below) at the cardinal points on a rectangle as well as a center point and allow for snapping of any anchor point of one view to any point of another while also allowing for offsets from this snap point for pixel-perfect precision.

Anchor Names

Earlier I mentioned aligning a multilined label’s top left corner 5 points to the right of an icon’s top right corner. Here is how to accomplish this…

Multilined Label

Notice that I’m aligning the label to the icon. You could just as easily do the reverse.


Going Even Further

JFViewPositionUtil’s high and low-level methods ought to satisfy all your view positioning needs, but if your app has some specialized effect that isn’t handled you might also find the pointForAnchorPoint:ofView: method useful. It retrieves the location (relative to the parent view) of any of the subview’s anchor points. Armed with this information you can create your own frames to position views just the way you want.

Grouped Layout Strategy

With this introduction to the class’ capabilities out of the way it’s now time to talk layout strategies.

While there is nothing wrong with laying out each control in relation to a sibling control it often makes sense to group controls within an otherwise invisible NSView/UIView and adjust the size of that parent view perfectly for the subviews it contains.

Why would you want to do this? This approach allows for a group view to be dynamically slid in between two others and to have them adjust their positions to accommodate it. Having to re-adjust dozens of controls in tandem is a lot harder than re-adjusting a single group view acting as the parent view for these controls.

JFViewPositionUtil offers the setHeightOfSuperview:toFitAllSubviewsWithMargin: method to help you in this regard. Think of this method as being like the UIView sizeToFit method except that it allows for an adjustable margin on the bottom of the lowest subview.

This method is also quite useful for adjusting the vertical height of UIScrollViews, even if you don’t plan to dynamically insert or remove group views within them. The logic has a special handler for UIScrollViews to set their content size in addition to their regular view size.

One last thing to note: The lazy-initialization approach I advocated earlier comes into play again here. Keep in mind that the group view needs to ensure that all its subviews are initialized and positioned prior to adjusting its own size to fit them. By going with lazy-initialization the group view doesn’t need to worry about the possibility of re-initializing its subviews.

Localization Concerns

As I mentioned earlier it was when I was localizing KEYBOX that I encountered difficulty with laying out my views. Japanese is a very compact language whereas French and Spanish are comparatively stretched out. English is somewhere in the middle.

The approach I took in version 2.0 was to use fixed size font, multilined labels to handle any text length and have any sibling controls appearing under them dynamically adjust their y positions to always be N points away. As long as the parent view had enough vertical room or was UIScrollView-based it worked like magic.


Animated Views

In case you were wondering, this class is also compatible with the animation systems of both OS X and iOS. Simply use JFViewPositionUtil to set the new position within an animation context and watch iOS do the rest for you.  For OS X you can use a view’s animator for the same effect or directly reset the view position at each progress step of an NSAnimation if need be.

Lastly, if you are developing an OS X project and use auto-resizing views (setAutoResizingMask:) you’ll be happy to know that they are completely supported as usual in much the same manner as animated views are.


In Closing

JFViewPositionUtil is the result of my own frustrations with dynamic, hand-coded views.  If you are equally frustrated with the difficulties of having to code your UI by hand but simply cannot rely on Interface Builder to meet your exacting needs JFViewPositionUtil might be the sweet spot for you. I invite you to give it a try and find out for yourself!

If you have any questions or comments please contact me at jay [AT] this domain.

I made this! – Rethinking Code Ownership

Except in more complex arrangements involving freelancers/contract workers the code that developers create obviously belongs to the company. When we talk about code ownership, we imply the knowledge to maintain that code. Code can be a very brittle thing and the developer who created it may be the only person who understands the background of why the code is the way it is.

I’ve been fortunate to have worked in many projects which took various approaches to code ownership. In fact I’ve witnessed both extremes of the spectrum and various points in between.  The result?  I’ve come to the inescapable conclusion that code ownership is not only a good thing overall, but that it really ought be an unalienable right for developers. I’m ordinarily open-minded and don’t consider myself a purist on most matters but this might be an exception.

The reason is simple, as in all things, when a person’s name is attached to a thing, more care will put into its making.

I’ve been developing professionally now for over 15 years. Long before movements like XP, TDD and Agile Development became buzzwords. These movements have introduced or at least popularized certain beneficial techniques but also some just plain bad ideas like backseat driving as a productivity booster and the topic of this post, code ownership or rather the movement against it.  As I said above I’m generally not a purist so I prefer to handle each problem on a case-by-case basis and not handcuff myself with artificial restrictions.

I could write a treatise about how religiousness has taken over the profession of development but in this article I just want to discuss the rationale behind the movement against code ownership and why I think it misses the point.  So without further ado…

 

Flight Risk

The biggest crux of code ownership is that of flight risk. What if the owner of a piece of code quits and takes his knowledge with him? What if he uses his knowledge as leverage to force a raise/promotion out of us? What if this? What if that?

There are a lot of “what if?”s out there. These scenarios could indeed play out but one thing that isn’t a “what if?” is that less experienced developers are going to make bugs and continue making bugs until they learn to fix them.

To counteract this possibility of flight risk it was proposed that total ownership of code be abolished. In its place various approaches have arisen…

  • 100% shared code. Everybody owns everything/nothing. If a bug is found anybody can fix it. If the code isn’t clean, anybody can go in and clean it etc… If anybody quits it shouldn’t impact the company at all, in theory. The only problem with this approach is it doesn’t work. Development is a complex endeavor and it’s simply not possible to know everything. It’s more often the care that developers will be fixing code they’ve never seen before let alone understand.
  • Team ownership. A project’s code is owned by the team. If one member of the team quits the others will pull up the slack. While not perfect, this is a more balanced approach. You don’t need to know everything, just the projects in which you participated.

It’s true that developers can pull up stakes and leave a company at any time (they aren’t slaves). If he or she has all the knowledge about a piece of code then that will be lost. Or will it?

Assuming the code remains, if a compiler can understand it well enough to carry out the instructions within, certainly a developer with some time can do the same. I’ve often inherited such code with little to no documentation. It takes time but not all is lost.

 

Going in Reverse – Keeping Developers Around

All other factors being equal, the more a person’s name appears in code the less likely that person is to leave the company. Developers are builders and we take pride in the things we build. We indeed become attached to them. That attachment, if it’s a positive one at least, can very well anchor us down.  And it’s a compounding effect!

80% of development is maintaining and extending existing code and the longer we work on a thing and the more code we own the harder it is to just leave it.  By abolishing code ownership you are actually discouraging this attachment from occurring and are arguably giving little reason for developers to stick around.

You might ask “Isn’t the attachment to the delivered project enough?”  The answer is “no”.  Attachments aren’t binary, they’re degrees, and the more there are the better.

If you fear that your developers will up and leave at any time you may have the much larger problem of a crummy work environment. Any great place to work will inspire people to stay.

 

Code Ownership = Code Accountability

One of the best properties of code ownership is that it allows the code to develop the developer. If I make a mistake (it’s been known to happen) and I’m tasked with fixing it myself I’m going to learn from the mistake and the likelihood of me repeating it in the future will diminish if not drop to zero entirely.

Remember, bugs don’t come into existence by themselves, it is we developers who put them there in the first place. Of course we didn’t do it on purpose, they were put there as a consequence of us not understanding all the circumstances in which our code would run. It follows that one of the best ways to prevent bugs is to learn from them by fixing them.

The alternative, is to have somebody else fix my mistakes in which case I might not learn much if anything. Adding insult to injury, the developer who fixes my bug has now been burdened by me and with each such occurrence will hold me in lower and lower esteem.

Personally, I would prefer to be held accountable for my successes and my mistakes.


Fixing other People’s Code

Ask any developer if he or she enjoys fixing other people’s code. I guarantee you that you’ll be given a resounding “NO”. I hate it too. It often feels unfair.

Over my many years of developing I’ve settled upon patterns that have proven themselves capable of creating robust code. I’m not perfect of course but I don’t leave a mess everywhere for others to clean up. I see it as an issue of discipline and I just don’t want to be a dick to others.

The fact is, in the same sense that you can’t become a programmer simply by reading a programming book you can’t learn from your mistakes if somebody fixes them for you and just tells you where you went wrong. You have to fix bugs to learn how to prevent them. I’ve fixed my share and I’m a better developer because of it.

 

Personal Projects

My most robust code is in my personal projects. If it wasn’t I’d be inundated with bug reports, which I cannot afford to deal with. I own not only the knowledge but the very code itself. Unless I open source all my code nobody will fix my mistakes for me so that code has to be the best.

Each developer is of course different but I suspect those who truly care about quality share the same experiences as myself in this regard.

Even developers who work in an environment where code ownership is considered evil should at least pursue their own personal projects during their off time and see for themselves which approach works best.

It might just give us cause to rethink code ownership.

Judging an App by its Cover – Techniques and Tools for Creating and Testing a Professional App Icon

When I redesigned the KEYBOX icon for version 2.2, I promised to write about the icon design approach I took. It’s taken me some time to get around to it but here it is. In this post I want to talk about optimizing your app icon so that it has greater visual impact in the App Store. This is not an article showcasing a handful of awesome icons, there are already plenty of those.

The Basics

Most sales of iPhone apps are made via the App Store app present on each iPhone. When designing your app’s icon, how it will appear in this store is of utmost importance and as you can see from the image below, there are four important elements that introduce your app to the world…

  1. Icon
  2. App Name
  3. Price
  4. Review count and rating
App Slot

 

People are visual by nature. Our eyes are drawn naturally to images and shapes.

When an iPhone user is quickly scrolling through a list of apps in the App Store, an icon that grabs the user’s attention may be the only thing preventing the remaining three elements and most importantly your app’s detail screen from being overlooked.

 

Before & After

The old KEYBOX icon is an example of how not to design an icon. It was my first attempt at iOS app icon design and, admittedly, a bad one at that. As you can see from the below image, it was flat and almost the same color as the App Store background. It’s almost as if it were hiding from the iPhone user and in retrospect it’s a miracle KEYBOX sold any units at all prior to the icon redesign.

Old KEYBOX Icon

Below is the new KEYBOX icon.

New KEYBOX Icon

I’m not claiming that it’s the most impressive icon out there but it’s a far cry from the original. I wanted to retain the spirit of the original icon (a secure place to safeguard your secrets) while also communicating how advanced KEYBOX actually is. Even though the image of a safety deposit box is familiar and trusted it was beginning to feel…. well, old.

The new icon keeps the signature keyhole (which has been there since the J2ME version back in 2005), and adds a foggy glass window through which we can just barely make out the many secrets represented by colored lights. The exterior of the box appears sturdy and the orange lit lock lamp communicates the box’s locked state. The grooved black panel rising slightly above the white box denotes that it is where the user unlocks the box. I could go on forever but what I’m getting at is the detail this icon now offers gives it a tangible feel and almost looks as if it could be plucked right out of the screen.

 

Real Testing

As you might have already guessed, when I redesigned the new KEYBOX icon I wanted to be sure it stood out from not only crowd but also the App Store itself. The most important advice I can offer in this post is this: From day one, understand how icons (not just your own) will appear in the App Store.

To demonstrate what I mean, the iPhone App Store (the native app, not the browser-based iTunes app page) offers two background colors, dark gray (#98989C) and light gray (#ADADB0). On the left, right and bottom sides of the icon is a drop shadow. Below is a blown-up image of the KEYBOX icon as it appears in the App Store. Compare it to the icon above and note the drop shadow on both sides and below the icon.

Drop Shadow Blown Up

Since translucency isn’t supported, you’ll need to emphasize your icon’s false sense of depth (the object casting the shadow) along these edges if you want a professional look.

 

Overcoming The Unnatural Icon

It should be obvious that an icon which doesn’t populate the bottom, left and right sides will look unnatural. We are forced to fill up those boundaries. I know I said this article wouldn’t be about existing examples of great looking icons but I just want to link to some creative icons that took this forced shape constraint and made something delightful with it. The lesson is let this constraint push you to be creative.

 

Porting Considerations

At some point you may want to port your app to the Mac, to Windows or maybe even to Android. At the time of this writing, iOS is the only platform that forces the rounded rectangle shape on us. If you’re porting your app away from iOS you’ll no longer be constrained this way. However offering the identical icon on a different platform can provide instant recognition with users already familiar with your iOS app so there is some merit in keeping the icon identical.

 

Standing Out

It goes without saying that you want people to notice your app. Once you have ensured that your icon fits well in the App Store you can now concern yourself with competing with other apps for attention. Below are some techniques other apps are already using. Your app icon should also follow suit.

  1. Using the drop shadow to provide depth.
  2. Using contrasting colors.
  3. Use alarming colors like red and yellow if appropriate.
  4. Using gradients to provide a sense of texture.

Below I’ll examine each of these techniques in detail…

 

Depth

As I mentioned earlier, people are visual and react to shapes and images. Objects that cast shadows appear to stand out. Since Apple renders a drop shadow under each icon we should use it by adhering to the rounded rectangle shape. The one element to be careful of is that this drop shadow also forces us to apply the correct lighting upon the object that is casting that drop shadow (from above, obviously). The only exception is when an icon is intended to be a flat window into a scene.

Another lesser used depth technique is the sink-into-screen icon.

Sunken Depth Icons

Apple’s Photo Booth and Newsstand apps are excellent examples of this. Rather than protrude out of the screen towards the user they sink into it. The Photo Booth icon cleverly uses a border to create a small booth/room and shows the floor to give a sense that it can be walked into. The Newsstand icon appears as the typical magazine stand one might find in a street kiosk. The only caveat with this approach is that it leaves less room for the objects within the sunken space. Lastly, a sense of depth can be achieved by casting inner shadows. KEYBOX’s black panel casts two such shadows onto the white box to which it is attached.

The worst way to destroy the sense of depth is to opt for Apple’s default glossy effects.  This effect encases your app icon in an chiclet-like button.  To turn this off, select “Prerendered” in the project’s Target Summary Window (near App Icons).  If you’re using a version of Xcode that doesn’t support this try setting the “UIPrerenderedIcon” preference to YES in Target Properties.

 

Contrasting Colors

The human eye is driven to contrasting colors. One of the best app icons※ to demonstrate this is the ever popular Temple Run by Imangi Studios. Its use of yellow and black helps it both stand out from the App Store’s gray background as well as pull the eyes of any iPhone user to it. Even if the game is not of interest to the user this icon simply cannot be ignored.

Temple Run App Icon

KEYBOX’s new icon also employs a contrast of white and black. The white contrasts with the App Store’s gray background and the black contrasts with the white.

 

Alarming Colors

Color psychology teaches us that some colors induce a sense of alarm in people. Red and yellow indicate spiciness, high temperature, danger, and even anger. Adding a white halo around these colors can amplify their effects. The topic of color psychology is too deep for this post but it is worth studying the effects certain colors have on a target audience and whether those effects are appropriate.

 

Gradients

In reality, your app’s icon is a flat array of pixels. To provide the illusion that objects in your icon are tangible use gradients. They trick the eye into believing that light is refracting off surfaces at different angles, angles that should only be possible if the object itself were not flat. Take the aforementioned Photo Book icon’s red curtain. It appears to ripple but of course this is just an illusion.

 

The Tools & Techniques

We’ve discussed theory long enough. Now for some tools and techniques.

As you are probably aware, the App Store requires that you prepare your icon in a variety of resolutions…

  • 57×57 for non Retina display iPhones
  • 114×114 for Retina display iPhones and iPod touches
  • 512×512 for the App Store (will be resized at display time to a smaller size)

Obviously you won’t make the same icon 3 times but will instead resize it to each of these resolutions. Some people dabble only in raster graphics for this but I prefer vector graphics perfectly rasterized at the end to the right size.

I might be the only developer who isn’t using Photoshop / Illustrator to create app icons. I like to support Indie Developers and I’m an Acorn user. As for my vector graphics needs I discovered Inkscape and SVG years ago and never looked back. Inkscape is originally intended for Linux and on the Mac it has to run as an X11 application. This leaves a lot to be desired in terms of look and feel but it is a very capable SVG editor and gives me numerical precision over all my icons’ elements.

If you don’t spend much time doing graphics editing and don’t feel justified in forking over the amount of cash to buy Illustrator check out Inkscape. If you’re already in possession of Adobe software or any other software capable of the job by all means go with what you have.

I’ve prepared an Icon Template SVG file in Inkscape that provides the dimensions and rectangle rounded corners just the way Apple likes them. You can use this as a container for your icon and to export the various raster graphics at their respective resolutions. If you inspect the SVG XML you’ll find the exportable area to use with the “Export Bitmap” function. In this file I used a 512×512 rectangle with rounded corners (rx and ry set to 70.0).

 

A Modeling Contest

My approach for judging the visual appeal of my app icons is much akin to a modeling contest. Up until now I’ve made it sound as if creating an optimized app icon is down to a science. Nothing could be further from the truth. As if tweaking this or that element in isolation would eventually yield the perfect icon. Models in a beauty pageant are not judged in isolation, they are judged in tandem against one another, and so must our app icons!

The steps described below put you in charge of a modeling contest, for icons!

  1. Scour the iPhone’s App Store and take full 640×960 screenshots of screens with the most attractive icons you encounter.
  2. Of all these icons pick what you consider to be the best four. Any given App Store screen can only display five apps so yours will be the fifth competing for eye-balls against these four.
  3. Using Acorn, Pixelmator or any other graphics editor create a 640×705 image within which you’ll drop each 640×141 app slot.
  4. Place your app icon in the middle slot. If your app is not already available in the App Store you’ll need to get creative and override another app’s slot with your icon. Don’t worry about the app name or other text, we’re just concerned with the icon for the time being.
  5. Walk away from your Mac for at least 15 minutes and come back to gain a fresh and unbiased view. Remember, you want to see what App Store patrons who are otherwise indifferent to your app will see.
  6. Judge which icon is the most attractive.

At the end of this process, if your app icon doesn’t even come close to contending identify why that is not the case. From there, decide what actions to take in order to close the gap.

I’d love to provide you with a template full of beautiful icons against which you could compare your own but I don’t own the rights to those icons. I can only provide you with these instructions for creating your own template.

In Closing

Creating an app is no small task and takes weeks if not months from beginning to release. Regardless if you are selling your app or giving it away for free you want to get it into people’s hands and everyday it is getting harder to gain the awareness needed to accomplish this. Your app’s icon is the gateway to impressing potential users and you owe it to yourself to put as much effort into it as you did your app.

Speaking personally, KEYBOX’s sales have more than doubled in response to the new icon design. I wish I knew what I know now when I first released it. Hopefully you’ll be able to apply these techniques from the beginning for your app.

 

※Temple Run app icon used here with written permission of Imangi Studios.

Open Source Code for Developing Sudoku for iPhone and OS X

My Love For Sudoku

I’m a Sudoku addict. My love for Sudoku has most certainly surpassed unhealthy levels.  Naturally, being a developer I at one point had an interest in developing my own Sudoku game just to see what it entails.

The concept of Sudoku is a very ancient one but the game’s recent popularity is attributed to the company NIKOLI which owns the copyright to the word “Sudoku” and the Japanese “数独” (lit: “number alone”) within Japan.

Game concepts, in and of themselves, cannot be copyrighted and to get around any copyright disputes I considered calling my game “9 Lives” and varying the gameplay enough by employing a strict rule of allowing up to 9 mistakes before the player loses. Essentially I was interested in making a Sudoku game for pros (no hints or anything).

However, I later learned through the Quinn/Tetris debacle that even though game concepts cannot be copyrighted, the owners of such games still show their legal fangs if you encroach on their territory and considering that my presence here in Japan is also where NIKOLI is based I reconsidered developing my own game.

That was 5 years ago, when I was just beginning to learn Objective C and OS X development. While cleaning some things up on my Mac I recently rediscovered my old Sudoku board generator code and it feels like a waste to just let it sit there unused.  Instead I decided to rewrite it (the original code is too embarassing to release) and donate it to others interested in making their own Sudoku games.

Most of the Sudoku games I have played only offer pregenerated boards. My code creates random ones each and every time. As such it depends on a random number generator, in this case my JFRandom utility class which is available on github.

If you are outside Japan and interested in making your own sudoku game check out my Sudoku Board Generator.

 

How To Use It

This one line is all you need to generate a random Sudoku board…

SudokuBoard *board = [SudokuBoardGenerator generate];

Outputting the resulting Sudoku board with NSLog will show the board in full like below…

7 1 8 5 4 3 6 2 9 

6 9 3 2 1 8 5 7 4 

5 4 2 9 7 6 3 1 8 

4 3 5 7 9 1 8 6 2 

1 6 7 8 3 2 4 9 5 

2 8 9 4 6 5 7 3 1 

8 5 1 6 2 7 9 4 3 

9 2 6 3 5 4 1 8 7 

3 7 4 1 8 9 2 5 6 


The board exposes 9 sectors (3×3 grid) and the numbers contained within for you to display in your game.  That’s all there is to it.  The details are all abstracted away from you.  If you have any questions please don’t hesitate to contact me at jay [AT] this domain.

Matt Gemmell’s 25 Rules for API Design

Yesterday Matt Gemmell posted a very comprehensive blog post regarding API design that I just had to share here. Although the post leans towards UI control design in Objective C these rules still apply to other varieties of APIs (Web, REST, etc…) and platforms.

http://mattgemmell.com/2012/05/24/api-design/

If you’re developing an API or component that might ever be consumed by other developers you would do well to bookmark this page as I just did!

Generating Random Numbers, Strings and Data in Objective C

Today I’m open sourcing JFRandom, a powerful utility class for creating random numbers, arrays of these as well as random strings and data.  It’s available for free download over at github.

I’ve been using this class in my KEYBOX product for nearly a year now and I can attest to its robustness.  JFRandom works in both ARC and non-ARC projects for both iOS and OS X.

Whether you need random data for encryption purposes, video game AI, shuffled music playback or just lucky lotto ticket numbers, JFRandom has you covered.

 

How to Use JFRandom

JFRandom is very simple so I’ll just illustrate one-liner examples of the main functionality below.

 

For single random numbers…

NSInteger number = 0;
BOOL worked = [JFRandom generateNumberBetweenLow: 0 andHigh: 100 intoReceiver: &number];

 

For arrays of random numbers…

NSInteger sequence[100];
BOOL worked = [JFRandom generateNumberSequenceOfLength: 100 into: sequence betweenLow: -1000 andHigh: 1000 withOnlyUniqueValues: NO];

 

If you need each number in the array to also be unique do this…

NSInteger sequence[100];
BOOL worked = [JFRandom generateNumberSequenceOfLength: 100 into: sequence betweenLow: -1000 andHigh: 1000 withOnlyUniqueValues: YES];

Note that creating unique number arrays can cause performance issues as the existing selection must be first examined for instances of the next random number to place within.

 

JFRandom also generates random NSData instances…

NSData *data = [JFRandom generateRandomDataOfLength: 16];

 

If you need the bytes to be signed rather than unsigned…

NSData *data = [JFRandom generateRandomSignedDataOfLength: 16];

 

And of course if you need a string full of random characters it’s this easy…

NSString *text = [JFRandom generateRandomStringOfLength: 64];

 

These are the basic capabilities of JFRandom.  There are a few more methods that allow for randomly picking of numbers within a pre-determined array etc…  Check out JFRandom now and save yourself the trouble of coding and testing this yourself!

iOS and Android Fragmentation – A Developer’s Perspective

Disclaimer: The impetus for writing this article is in response to the naysayers in the Android camp who would have consumers and developers alike believe that Android fragmentation is a myth. I’m here to prove that it is not only very real but very costly to dismiss as a myth. In short, I want to arm people with the correct information. I’m an iOS developer and an Apple fan. I have never owned an Android device although I’ve participated in a development project where Android fragmentation reared its ugly head and I’ve also developed extensively for feature phones which exhibited the same characteristics as Android with regard to fragmentation.

What Is Device Fragmentation?

It helps to define fragmentation before going any further.

In a broader context, fragmentation is simply taking one thing and splitting it into fragments. In the context of technology, fragmentation is the act of offering instances of one thing that, while labeled as a single brand, are distinct enough from one another to be considered separate.

By this definition Android is fragmented, as is iOS (albeit to a much lesser degree which will explored later on), and even computers.

Android Fragmentation

So what makes Android so fragmented?  The short answer: Android device makers.

They have to fragment Android in order to compete. Consider the alternative. If Sony offered essentially the same device as Samsung with the same technical specs what advantage would there be in purchasing one over the other? The only alternative would be to compete only on price but that could start a price war resulting in diminished profit margins for both companies. It is therefore in the interest of every serious Android device maker to innovate and outgun its competitors in the Android space (as well as against the offerings of Apple and Microsoft).

Now that I’ve established that the only thing Android device makers share in common is the word “Android” and that they have little choice but to fragment, it’s time to ask the next pertinent question: How does this fragmentation actually take place?

Since Google doesn’t itself manufacture Android devices (Google does work closely with some manufacturers however) there is a lot of wiggle room for device makers. To understand this better let’s look at the breakdown of an Android device…

  • The maker specific hardware
  • The base Android OS
  • The maker specific platform added to the base Android OS

The hardware plays the biggest role in fragmentation. Device makers cater to their respective markets. Some devices lack bells and whistles in a bid to remain affordable for consumers not willing to pony up for a premium phone for instance. At the other end of the spectrum are the Samsungs and Sharps of the world. Below is a list of some areas where makers customize their devices.

  • CPU speeds
  • RAM memory capacity
  • Antenna strengths
  • Storage space
  • Storage I/O speeds
  • Display resolution
  • Display color output
  • Display input accuracy/sensitivity
  • Presence/absence of hardware accelerated graphics
  • Presence/absence of various ports for external media and devices
  • Camera resolutions
  • Battery life
  • The list goes on…

The base Android OS is arguably the area with the least fragmentation. This is the part for which Google is responsible. Some like to view the low penetration of the latest Android OS on newer devices as a kind of OS fragmentation. It’s not quite the type of fragmentation I want to discuss here but it is true that since device makers stand between Google and the consumer, OS updates don’t occur as optimally as with iOS.

The maker specific platform that is slapped on top of the base Android OS is an interesting topic. It renders Android more a meta-platform than a real platform. The Kindle Fire is an example of an Android device that takes great liberties with regards to the UI. In fact, it almost doesn’t expose its Android heritage at all. The look and feel of this layer is one apps that hold themselves to high standards should strive to match when possible and this forces the apps to choose certain devices to support. As an aside, Ars Technica recently reported how Amazon’s market leadership is rendering Google’s control of Android weakened.

 

iOS Fragmentation

Okay I’ve discussed Android a bit, it’s time to take a look at iOS. Unlike the multi-party affair that is Android, iOS and the devices on which it runs are made only by Apple. While this leads to a much less fragmented platform, iOS is not perfectly immune to fragmentation.

Each new iOS device boasts a slew of hardware improvements over its predecessor and with them, you guessed it, fragmentation. Even at a single point in time there are 3 flagship iOS devices: iPhone, iPod touch, iPad with different specifications.  Most of the elements I mentioned for Android above are present on iOS as well.

Supporting many generations of iPhones or iPads can be tedious. However one generation per year is more manageable on the pocketbook. The 4th generation iPod touch is relatively cheap at $199 US and aside from its lack of telephony components is essentially an iPhone 4 and can substitute it for most testing.

Wikipedia has a comprehensive list of iOS devicesand their specs but I’ll focus on the types of fragmentation I have personally found on iOS.

  • The color output on my iPod touch is slightly bluer than that of my iPhones and I’ve had to take that into consideration when designing icons and graphical elements.
  • The iPod touch has only 256MB of RAM despite offering Retina Display resolution which means developers of memory hungry apps need to hand test them thoroughly and optimize for these constraints.
  • GPS accuracy diminishes with the iPod touch and Wi-Fi only iPad since they cannot avail themselves of cell tower triangulation.

And that is basically where fragmentation ends.

To the delight of developers, the resolution of the iPhone and iPod touch has remained 320×480. When Retina Display was introduced the only change was the resolution unit from pixel to point (1 point being a 2×2 pixel area). The new iPad has followed the same approach of staying with a resolution of 1024×768. The iPad’s split view design with its left side table view having the same width as the iPhone’s screen makes it easy to port iPhone apps to the iPad while retaining the same look and feel.

Why should all this make developers happy? We have only ever needed to consider one resolution for our apps on each device class. This gives us the time and freedom to strive for a pixel perfect look without having to contend with container based stretching and contracting layouts that adjust to match various resolutions but look less polished.

 

Ramifications of Fragmentation

I make fragmentation sound like a bad thing. I indeed view it that way. As a developer fragmentation introduces more work and incurs more cost to deliver a quality product.

You could argue that fragmentation is innovation by a different name and that it is good for consumers. More choice, more competition and all that. However there are also grave demerits for consumers. The sheer selection of options can be a dizzying experience comparable to buying a DIY computer with all the trimmings. At the time of this writing Google lists 225 Android devices on its web site.

 

My Experience with Fragmentation

I now want to take the word “fragmentation” from being just a distant, technical concept to what it is really is, a mental and financial burden. Let me share a couple real live experiences I have had with fragmentation. Only then can you relate to the pain and truly understand what awaits you.

Before making its way to the iPhone, KEYBOX was a J2ME app for the Vodafone Japan market. J2ME was, in its day, the only real platform for mobile phone development (BREW wasnt a real competitor). But it was fraught with the identical fragmentation issues that Android developers now face. Each device had a different screen resolution, different color output, different CPU etc… But it was worse, some devices didn’t even support transparent/translucent PNG files or floating point math operations. There was no rich UI toolkit to speak of and if you wanted to make information-based apps with text boxes, buttons and the like you had to contend with the limited selection of device-specific controls with different look and feels. Sun has never been a leader in user interfaces the way Apple or Adobe/Macromedia have and didn’t think to standardize the UI the way Macromedia did with Flex.

I hold myself to a higher standard so rather than settle for inconsistent controls I rolled my own tile-based UI kit that detected the optimal dimensions for windows and such for each device. It was a pain to say the least.

J2ME KEYBOX J2ME KEYBOX

 

I later parlayed my own creative development into professional work opportunities in mobile. The most challenging of which was a DoCoMo J2ME app named Harumin. Harumin was an avatar based television guide and remote control app for the then upcoming Foma 900i series.

(Harumin character – Designed by Spring Design)

Of the 5 devices in this lineup the flagship was the Sharp SH900i and the worst was the Fujitsu F900i. Getting the same code to send infrared signals to a TV from all the handsets was impossible. The Sharp unit was too fast and the Fujitsu unit too slow. We ended up writing device detection logic to throttle the speed. Antenna strength was flaky with the Fujitsu unit and caused us to refactor our network communications logic and last but not least button clicks were interpreted as presses on the Fujitsu unit whereas all other devices considered button releases (the correct way) as clicks.

Long story short, had we not had access to all the devices there is no way we could have made the app accessible across the entire series. Fragmentation was a pain for us, not a plus. It cost us double the time to develop and test our app because of it.

Going Forward

Where I fault Android is that it had J2ME’s failure to learn from but chose not to. Google has now dug itself into a hole from which it will prove difficult to escape.

What attracted device makers like Samsung, HTC, and Sharp to Android was its openness/cost and branding. However if Google were to begin dictating conventions and standards to device makers in a bid to steer Android in a single direction the way Apple does, it may find them abandoning Android and perhaps even spawning a competing fork of it. Even without such moves, Amazon has forked it and it has been speculated that the openness Google prizes could very well be Android’s undoing.

 

Cutting Apple Some Slack

Regardless of how you feel about openness you cannot deny that Apple is in an enviable position. It only needs to answer to developers as it steers the iOS platform forward. There are no device makers to appease.

Apple has kept fragmentation under control but has fallen victim to criticism concerning its tight control over its platform.

Prior to the iPhone if you wanted to make slick games that reached the masses you had to buy a development kit from Nintendo at the ever affordable cost of tens of thousands of dollars. And you had to prove you were worthy of one as well. Nintendo’s pre-sale curation process makes Apple’s look like the wild wild west.

Coincidentally, the only reason one would want to make a game for a Nintendo console like the Wii is the almost complete lack of fragmentation. If your game works on the development Wii it will work on every Wii unit in the wild. The savings in development, testing and support time might just justify the price if you have a hit game and have the money upfront. The Android of this scenario is PC gaming with DirectX or OpenGL which is harder (testing graphic cards etc…) but doesn’t require permission from anybody.

All in all, Apple has successfully struck a balance between the democratization of development for the masses and the offering of a simple platform. For less than $100 a year (and the one-time cost of a Mac and an iPhone) developers can make games and apps. $100 is quickly recuperated even with zero advertising/marketing.

The App Store is such a success that even Nintendo is feeling the heat of Apple’s foray into portable gaming.

Android has tried to emulate the success of the App Store but it has been hit and miss. Independent developers cannot afford the full gamut of even the current generation of Android devices and must pick and choose which devices to target if they are serious about ensuring full support. Such choices are not trivial and involve much research into demographics and device preferences. By the time the project is finished the devices against which it was tested are no longer the latest and greatest as well.

Potential for Further Fragmentation

The rumors of an iPad mini or a slightly larger iPhone never quit. It’s called linkbait and puts food on the table of many a tech writer. Never say never, but so far such reports haven’t panned out. Just recently mock-ups of a purported iphone 5 with a longer screen were leaked. If Apple does go this route it’ll only be if it has found a proper way to allow for existing apps to work well on it and for it to not fall out of people’s pockets. Apple is famous for internally testing products before unleashing them on the public and the form factor we see now exists because it makes sense.

The reason so many deviating form factors exist on Android is not because people are clamoring for them. The marketing departments of device makers are simply looking to “BIGGER is better” as a way to make the public buy their offerings.

It’s still too early to conclude which is better but rather than listen to pundits I’m happy to sit back and watch the market decide.

Conclusion

Android and the innovation it promises are great for the average technology enthusiast but for developers this means dealing with the resulting fragmentation. This can come back to hurt consumers as well. We developers either need to raise prices to justify buying more devices (recipe for failure, especially on Android) or choose certain devices and hope the user base will be big enough.

Apple’s approach is simple and well thought out. It doesn’t need to eliminate the problems that saddle Android because it never created them in the first place. The fragmentation that is present is emergent from obsoleting older models of same device but minimal and even under a severely constrained budget a developer can target a single device and still reach millions of users around the world.

 

The Case Against Universal Apps

Since the advent of the iPad, iOS developers have had the option of distributing universal apps that bundle logic intended for both iPhones and iPads.  But is this a good thing?  In this post I quickly discuss the outcomes of going universal and why they might or might not make sense for your app.

Pricing

You’ve worked hard on your app and you’d like to be fairly compensated for that hard work.

It’s a known fact that iPad users are willing to pay more than their iPhone counterparts for apps specifically designed for the iPad.  If you go universal you’ll have to choose a single, shared price for both devices.  Considering the amount of effort you put in to making the iPad edition of your app that much better for the iPad don’t you think you deserve better?

To add insult to injury, an iPhone user who purchases your universal app will get it for free on the iPad and benefit from the iPad specific parts.  So instead of earning 99 cents for the iPhone edition and $1.99 for the iPad edition you’ll only receive 99 cents, period.

Pricing Experimentation and Sales

You’ll likely be experimenting with your price to find the sweet spot which generates the most revenue.  This number can never be the same on both device classes due to different demographics.

And what if you want to offer a sale for just one device class to bring more awareness to it?  You probably have already guessed that with a universal app you will have to offer your sale price to users of both device classes.

App Size

Why should an iPhone user consume storage space for the iPad specific logic or vice versa?  Storage is at a premium on these devices already.

Code Complexity

Your iPad logic will be living side by side in the same project as that of your iPhone.  You’ll need to detect the device class at runtime and switch between logic.

Staged development

If your time or development budget are strained, you can focus on one device class first by not going universal.  You can determine your app’s popularity after release and decide later on if the other device class warrants a port.

App Store Ranking

Apple views universal apps as being distinct on the iPad and iPhone.  They may share common logic but from the user’s perspective the UIs are very different and any reviews they give reflect the experience of only one of them.  Accordingly Apple separates the ratings and reviews of both device classes in the App Store.  Ratings are believed to major play a factor in App Store ranking so having them separated eliminates any potential for boosting your rank by opting for a Universal app.

When do Universal Apps make sense?

If you have a very simple app that you know will always be free the demerits I mentioned above don’t warrant as much concern.

One merit of going universal is that you can call your app by a single name without appending “for iPad” or “HD” to the title and this can make your app easier to find in the App Store.

Conclusion

In many cases Universal Apps don’t work in favor of developers and in some cases they don’t make much sense for users either.  Careful weighing of concerns should take place first before you commit to either approach.

One thing is certain however, divorcing an already universal app into two entails a lot of effort and can cause confusion for users.  Marrying two editions into a universal app, should circumstances later warrant it, is much simpler.  Just like marriage, you should stay single until you’re absolutely sure you’re ready for it.

Agent App – How To Prevent A Mac App Icon From Appearing On The Dock

If you’re developing a Mac app that runs in the background most of the time (in other words an agent app) you typically don’t want to your app’s icon to consume space on the dock.

Luckily for us, achieving this is quite trivial.  Just follow these steps…

  1. In Xcode (4.3 for the purposes of this post), open the Project Navigator (the folder tab under the Run button).
  2. Select your project (the parent item with the blue print icon).  This opens the project details view.
  3. In the project details view select your app’s main target (under TARGETS) and select the Info tab.
  4. If it is not already present add an ‘Application is agent (UIElement)’ item under Custom Mac OS X Application Target Properties.
  5. Set this item’s value to YES (as shown below).

Application Is Agent

 

And you’re done!

From now on, whenever you execute your app its icon will no longer appear on the Dock or in the Alt + Tab application switcher.

Update to JFUrlUtil

Just a small update regarding the JFUrlUtil URL encoder for Objective C I introduced recently:  I recently encountered URLs in the wild containing the “@” character and accordingly have now added support for encoding it.

The updated JFUrlUtil is available here.

If you find any URLs that don’t encode properly please inform me (jay@jayfuerstenberg.com) and I’ll improve this utility.

Singleton Pattern in Objective C

Objective C unfortunately does not support the singleton pattern with which Java developers are familiar.  The reason stems from the fact that there are no private methods in Objective C to prevent the init constructor method from being invoked.

There is however a simple hack that can provide the benefits of the singleton pattern in Objective C.  Singleton classes tend to be managers of data so let’s go with the class name JFDataManager in this example.

 

Going Global

Since Objective C doesn’t support the singleton pattern we have to resort to using a global variable the way C does.

A global variable can be referenced from anywhere in the application and since we want to discourage the direct manipulation of this global variable we need to hide it.  The best place to hide it is the one place nobody will look, in definition file for that class, JFDataManager.m.

Doing so will render it unlikely of being referenced since we’re never supposed to #import or #include *.m files.  Note that I said unlikely.  Technically any inquisitive developer can find and reference it.

The declaration might look something like this…

JFDataManager *__JFDataManager_sharedInstance__ = nil;

Since the class name was previously declared in JFDataManager.h this instance is completely legal.  Now since we’re dealing with global variables there is the risk of name collision so it’s good practice to go with an instance name that includes the class name as I’ve done above.

 

Exposing It The Recommended Way

The convention for telling developers that they should access the singleton instance and not instantiate their own is to offer a class method beginning with the word “shared”.  You may have noticed a sharedApplication method exposed by the NSApplication and UIApplication classes.  You’ll want to follow this approach.

JFDataManager will expose the below method…

+ (JFDataManager *) sharedManager;

The implementation of this method will return the shared instance and if necessary lazy-initialize it like this…

+ (JFDataManager *) sharedManager {
	if (__JFDataManager_sharedInstance__ == nil) {
		__JFDataManager_sharedInstance__ = [[JFDataManager alloc] init];
	}
	return __JFDataManager_sharedInstance__;
}

 

Getting the shared instance is as simple as invoking the sharedManager method.  That’s really all there is to using the singleton pattern in Objective C.  It involves a bit of trickery but Objective C developers using your class will enjoy the same benefits Java developers already do.

 

URL Encoding In Objective C

A new project I’m working on uses NSURL to a great extent and as useful as that class is, it has one sour point.  It is unforgiving of improperly encoded strings when instantiating an NSURL via the URLWithString convenience constructor.

Naturally I needed an encoder that would escape the unsafe characters.  There is a decent selection online but they each lacked a few properties I need in my project.

  1. The domain + path portion needs to be left alone (no conversion of slashes etc…).
  2. Any previously escaped sequences (like %20) need to be left alone and not have the percent escaped again (like %2520).

I’ve given up looking for an existing solution and rolled my own, which I now share with you!

My implementation is called JFUrlUtil (Download) and is open sourced under the Apache license.

 

How it works

JFUrlUtil features a single public method called encodeUrl.  The approach it takes is basically to iterate over each character in the URL string you provide and escape where appropriate.  It is quite performant as it avoids invoking NSString’s stringByReplacingOccurrencesOfString:withString: method for each unsafe character.

Compatibility

I’ve tested this implementation against tens of thousands of URLs and have yet to find any encoded URL capable of causing NSURL to frown.  If you can find one I didn’t anticipate please let me know (jay@jayfuerstenberg.com) and I’ll gladly update my implementation.

 

When To Localize Your iPhone App

In the past I’ve highlighted some software design mistakes made by others and today I want to point the finger at myself and talk about a mistake I made in localizing my first iPhone app KEYBOX.  It is my hope that this article will help others avoid the same pitfalls I experienced.

I made KEYBOX to scratch a personal itch (digital privacy) and it was first released in 2005 as a J2ME app for Vodafone Japan’s market.As such it was never localized to any language other than Japanese.  That all changed this year when I ported it to iOS.  As the App Store is an international affair I naturally would like KEYBOX to benefit as many people as possible.  The main barrier to this is of course language.

For release 1 I decided to localize KEYBOX into the 4 languages with which I am familiar: English, French, Japanese and Spanish.

I now believe doing so this early was a huge mistake as it introduced two issues for me: serious delays in releasing and numerous layout changes.

In localizing KEYBOX, I underestimated the amount of effort it would take.  There are over 200 text snippets to translate from English.  Using online dictionaries to double check my translations and searching for real-world instances of each text snippet before issuing the final check of approval for each takes upwards of 20 hours for each language.  When you’re only doing this on the side (weekends and some evenings) you can imagine how much it delays the release of your app, which is otherwise feature complete and ready to go.

And then there was the EULA!  KEYBOX is unique in that it requires a rather lengthy EULA to protect myself from users who might be less than responsible with it.  Writing the English version was an experience in its own right.  Writing it in Japanese would’ve been a train wreck without help from my loving wife (also Japanese) and it took over 30 hours spread across 3 weeks.

An interesting surprise was that people in countries whose languages are not yet supported still download KEYBOX, and in droves!  Italy is perhaps one of the biggest markets and KEYBOX isn’t even in Italian yet.  I don’t know if support for Spanish and French is what makes this possible (the Romance language connection?) as KEYBOX is about privacy and I don’t solicit my users for such information.  While I’m sure that supporting multiple languages opens the door to more people enjoying my app, having so many languages supported from version 1 is perhaps less important than I initially thought.

Now to the issue of layout…  In comparison to English, Japanese can be an extremely compact language and most words are only 2 kanji characters in length.  And then there are French and Spanish whose words tend to be much longer than their English counterparts.  This naturally leads to sentences that expand and contract in length depending on the user’s locale.

Before translating the text I was tempted to avail myself of iOS’ ability to auto-adjust font sizes for a statically sized label.  I figured the sentence length wouldn’t vary so much and that an auto-adjusting font size could handle that difference.

I could not have been more wrong.  Doing so resulted in text so small that it was rendered unreadable and sometimes text that gets clipped off by the boundaries of the container label.

I learned, the hard way, that multilingual apps really are better off having multi-line labels with a fixed font size.

Going multiline however introduces a new problem.   It forces us to position controls spaced far enough from each other to compensate for the wordiest languages whose labels will expand the most.  Release 1 of KEYBOX followed this approach.  It worked for the most part but it took a lot of manual testing across languages to make sure the text was readable and that there were no overlapping elements.

I knew that I couldn’t take this approach forever and for release 2 I decided to change tactics.  I developed a high-level, goal-oriented layout utility class that lets me accomplish tasks such as “place this text field 10px under that label and center it on screen” or “left align this label 5px to the right of that icon”.  As a result I no longer have to consider the pixel locations of positionable elements across all locales at once and can focus more on the general look of the UI.  In some ways it works like HTML with the end result being one element following the last but unlike HTML it still retains simple, pixel perfect control.

 

Example:

KEYBOX 1 Without Dynamic Layout

KEYBOX 1 – Without Dynamic Layout

 

Keybox 2 import export

KEYBOX 2 – With Dynamic Layout (Text is directly under cloud image and the warning icon is to the left of the text)

 

I intend to open source this layout engine for those who want to maintain a professional layout for their multilingual apps but my best piece of advice would be to release one language at a time and just get your app out there first!  From there on, you can roll out new languages gradually.

How to Get the Local IP Address of an iPhone 4S

After a long 3 weeks of waiting, the iPhone 4S I pre-ordered has arrived and I’m in the process of thoroughly testing Release 2 of KEYBOX against it.

Today I have found what may be an issue with finding the local IP address of the iPhone 4S……. and a solution that worked for me.  KEYBOX has a built-in web server for exporting and importing backup files and it uses the IP address retrieval technique described in Erica Sadun’s wonderful book The iPhone Developer’s Cookbook to serve and accept these files.

In at least my case that technique is no longer usable for the iPhone 4S only.  The issue, as far as I can tell is that appending “.local” to a host name and attempting to retrieve the IP address via the gethostbyname function results in a NULL pointer to a hostent structure.  Removing the “.local” works but the IP address returned is not local and is not accessible from my Mac, as shown below.

Old gethostbyname

I could not reproduce this issue on my other iOS devices and googled until I stumbled upon the below alternative approach by Zach Waugh.

http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone

Thanks to Zach, I am now again able to retrieve my iPhone 4S’ local IP address.  I have also tested this approach on my older iPhone 3GS and my 4th Generation iPod with positive results.

New gethostbyname

Hopefully I am alone in this issue but if others are experiencing it also, give this approach a try!

Amazon S3 Server Side Encryption Flawed

Amazon recently announced a new server side encryption facility for their popular S3 service.  It employs AES-256 to encrypt objects much the same way KEYBOX does with secrets on your iPhone.  In and of itself there is nothing wrong with this, except perhaps the marketing.

My biggest gripe with Amazon’s server side encryption solution is how they promote encryption as something best not done by the client.  They cite messiness and difficulty as reasons for this.

It’s Called Wiretapping for a Reason

The objects transferred to/from S3 should be encrypted end-to-end.  They traverse a wide array of devices on their way from the client to S3 including home Wi-Fi networks, ISP networks etc…  Each of which may be monitored.

The only way to be certain the objects are kept secure is to perform encryption on the client side before any objects make it out onto the network.  If HTTPS is available, it should be used to shuttle the data to S3  (I can find no indication that the objects transferred to and from their servers are encrypted en route, as in HTTPS).

The Value in Encrypted Storage

Once the objects are stored in S3 there still may be value in encrypting them.  Machines break, get hacked into, get confiscated by law enforcement.  If you need to encrypt data in the first place it’s a good bet you want to be able to provide guarantees that it’ll remain secret despite these threats and not being the true master of the physical machines in which this data resides.  From this perspective server side encryption as an additional layer of security is valuable.

Conclusion

Everybody knows security is hard.  To pretend otherwise is irresponsible.  Amazon should exercise more caution in how it promotes this facility and not try to convince developers that it’s a magic bullet for their encryption woes.  The old adage: If you want it done right you gotta do it yourself applies here.

Sites Folder in Lion Missing

A lot of changes have been made to Mac OS X in Lion, some of them good, some bad, some just confusing.  Like this one…

I noticed today that the Sites folder under each user account’s folder is missing.  Upon further inspection, it seems it must be generated by turning on “Web Sharing” under the Sharing icon within System Preferences and pressing the “Create Personal Website Folder” button.

Pressing this button creates the Sites folder and the button is altered to read “Open Personal Website Folder…” as shown below…

Sites folder creation

I hope this tidbit helps people experiencing the same confusion I was.

How do I price my software?

I found a great resource today for software developers struggling to figure out how much to charge for their hard work.

Ironically, the book, Don’t Just Roll the Dice: a usefully short guide to software product pricing, is free as a PDF download.

Neil Davidson is articulate and explains in simple terms the factors to consider when pricing your software.  It’s well worth the $10 Amazon is currently charging for it and I intend to compensate Neil for his insights.