The good folks at the Apple store on Regent Street have given me permission, along with a bunch of other talented app developers, to promo one of my apps. Pop down to the store this Wednesday (7th) where I’ll be doing a very brief presentation of SafeJourney for iPhone.
Speaking At LiDG

So my first iOS speaking appearance went down on Wednesday. The topic was “An Introduction To Multithreaded Applications Using Grand Central Dispatch”. Many thanks to the 80-odd people who turned up and all the positive Twitter feedback that it resulted in.
As promised, the presentation notes are now available. There were some last-minute time restraints put upon me so I couldn’t go into the level of detail I had planned so if you have any further questions, feel free to drop a comment.
Working With Blocks In Objective-C
Blocks, are an interesting concept in Objective-C that can be used in many ways. As a quick starter, if you’ve heard of or used “closures” or “anonymous functions” in other languages, you should get the feel of what they are any what they can do. At the simplest level, they allow you to group multiple lines of code together which can be passed around your app with much the same flexibility as you might use simple variables.
So why is this useful? Well, there’s many reasons but, in the attempt to make this a bit more readable, I’m going to go through a few use cases for blocks and hopefully, by the end, you’ll want to start optimizing your apps to make use of them. But first, what’s a block look like? This:
^{ // some code here }
Fairly simple. The caret (^) defines a block and then curly braces contains it. A slightly more complex example would be the following:
typedef int (^IntegerComparisonBlock)(int i, int j); IntegerComparisonBlock whichIsGreaterBlock = ^ int (int i, int j) { return i > j ? i : j; }; NSLog(@"%d", whichIsGreaterBlock(1, 3)); // 3
Firstly, I’ve created a type definition for a certain format of block which will be available as type IntegerComparisonBlock. Defined at the end of the typedef are the parameters IntegerComparisonBlock‘s will expect, separated by commas. These blocks will also return an integer which is defined at the start of the definition.
Ok so we’ve got a block type. Now to actually create one based on it. The second line does this and calls it whichIsGreaterBlock. Following the caret, the correct return type and parameters are defined and then a bit of useless code that just returns the larger of the two. The final NSLog statement shows how it can be used.
As useless as that example was, you should now have a grounding on what a block is and how to create one that has a return type and accepts typed parameters. Now onto that use case list I promised…
Using Blocks In Place Of Delegates
Because blocks allow pieces of code to be sent around your application as one, they can greatly lessen the amount of code required to have one class do something based on what’s happened in another. Creating custom protocols, defining a delegate object, firing commands at that object and then another class defining themselves as that object works great but is quite cumbersome when maybe you only want a small amount of code to be executed. This is where using blocks can cut down on code. All you have to do is instantiate the second class, pass it some code contained within a block which you want to be run when that class has done it’s thing and then the second class can just call that block by itself when it needs to. This reduces the connection between the two classes and does away with the delegate object. Here’s a diagram which illustrates the differences:

Using Blocks With Grand Central Dispatch (GCD)
This is more an example of where blocks need to be learned rather than how it can change your standard coding but if you plan to be running your code on multiple threads, you’ll most definately be looking into using the libdispatch library and if you do that, you’ll be using blocks. A lot.
Grand Central Dispatch is a blog post of it’s own, but to illustrate how to implement in-line blocks, the following, simple GCD example should give you a good idea:
myQueue = dispatch_queue_create("com.davidfox.myqueue", NULL); dispatch_async(myQueue, ^{ [code to be run on another thread] });
Writing Blocks In XCode 4
The syntax of blocks can be quite difficult to read at first. Writing your own can end up in a bit of messy trial-and-error to see what actually works. Additionally, things like writing your own blocks which are stored within a variable to be reused multiple times can be very wordy. However, if you’ve got XCode 4 installed, you’ll find some great code snippets in the snippets window which give you the skeleton code for writing different types of blocks. Try dragging a few into your code; it’ll clarify things further.
Multiplayer Noughts & Crosses Over Bluetooth With GameKit
I spent a bit of this weekend playing around with the GameKit library in iOS. It’s actually fairly straightforward as long as you’ve planned your project well.
Anyways, the ultimate turn-based strategy game has been the outcome. Here’s a quick video of what I came up with…
(Sorry for the shakey footage)
Like I said, the game uses Apple’s GameKit which took about 90% of the development time to implement. At the heart of things is the GKSession class which, even more so than the rest of Apple’s components, makes heavy use of the delegate pattern. It’s what comes up with the list of nearby peers, establishes the connection and sends and receives packets.
To keep all this stuff out of the way of actual game logic, a separate class creates and handles the GKSession stuff. I also created a few custom delegates in this class which the main game sets itself to to be notified when packets containing the other player’s moves have been received.
Retrieving A User's Friend's Photos With The Facebook API
This is bullshit. The new(ish) Facebook Graph API is riddled with problems. Particularly when you want to grab photos your logged-in user’s friends have posted. In case you’re not familiar with the way security settings go when using the API, your application basically defines a comma-delimited string of permissions which you will want the user to grant access to. The values you specify here will influence details which show up in the “Allow this application to access your information” screen in Facebook.
First problem; when you define these, you define them in a normal string. Any typos result in an error when your app launches. Wouldn’t it be better for the API to contain a class of constants so not only can we ensure our permissions are correct, but we can also get a nice list of the available permissions when using autocomplete?
Second problem; and this one kind of makes problem one seem pointless but… there’s typos in the DOCUMENTATION for the available permissions! WTF!? Take a look at the following screenshot from the official graph api documentation page…

So this page was the most valuable screen for me when developing a fairly complex Facebook application. I knew I wanted to grab the user’s friend’s photos so I copy and pasted the “friend_photo_video_tags” and “friend_photos” into my app’s required permissions. Sounds like a good idea but then when I try to access that data, I get an empty array back.
Something wrong with my code? User has added additional security settings somewhere? Parsing error? I wracked my brains for a while and then the problem emerged… The above documentation is just plain wrong.
I kid you not, it turns out “friend_photo_video_tags” should be “friends_photo_video_tags” and “friend_photos” should be “friends_photos” (plural ‘friends’ instead of singular ‘friend’). How did this get past the Facebook API team and cause me to waste time trying to fix it?
On top of this, I’m finding instances where, even with the correct permissions set, I still get dodgy data back. To correct this, you should include ALL of the above four permission ID’s. Not ideal as I’d like to keep the amount of data I’m asking the user to disclose to a minimum but what can you do?
So Facebook… please put these values in a constants file and when you do, make sure they contain the correct strings!
UPDATE
Since writing this post and leaving a message on the Facebook developers page, it looks like the admins have updated the documentation to the correct values making this post completely pointless and not really worthy of reading. Sorry but you’ll just have to trust me that their documentation was once wrong!
UPDATE 2
The Facebook API documentation admins have deleted the post which I mentioned above that pointed out the permissions mistake! Bit dodgy…
Building "When And Where?"
So, “When And Where?” has just gone live and it’s my first application to be submitted to the iTunes App Store. All in all it took about 2-3 days of free time to put together, stress test and debug.
I thought it might be interesting to share some experiences about building an application like this…
Using Core Location And Web Services
The first thing I thought about that might cause some headaches was basically just working with external data and using the network. There’s lots of things to worry about and many different scenarios the iPhone might be in that would cause unwanted behaviour. What if the phone has no signal? What if Core Location can’t zone in to a particularly accurate approximation of the phone’s geographical location? If this application was going to be useful for a good range of users, from those using an iPhone like the latest O2 business phone to those who simply wanted a more convenient way to meet their friends, the app would have to be intelligent enough to accomodate the various situations the handset might be in.
Not only does not dealing with these issues result in an unpleasant user experience, it’s also grounds for your app being rejected by Apple.
In all circumstances, Apple’s documentation is generally top-notch. Entering any API or class name into the documentation window in XCode brings up all the usual information but also, sample projects created by Apple to help out with things. One such project which was very helpful was the “Reachability” project. It demonstrates in a very concise way, how to detect whether a phone’s network is available and, separately, if they have a working Wi-Fi connection amongst other things.
Ok, so I’ve ran this code on application startup and an alert will be shown if there’s no connection. But what about finding out the phone’s location and then displaying information about nearby places? Well for the phone’s location, Apple’s built-in CLLocationManager class is super-easy to use. Here’s a quick bit of code…
CLLocationManager *locationManager = [[CLLocationManager alloc] init]; [locationManager setDelegate:self]; [locationManager startUpdatingLocation];
I’m not going to go into too much detail, but these three lines of code create a location manager, set the containing class to it’s delegate and finally, just start trying to figure out where the device is. Additional delegate methods are then defined, the most important one of which looks a little like this in my project…
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if (newLocation.horizontalAccuracy <= kCLLocationAccuracyNearestTenMeters) { // we've got the device's location correct to the nearest 10 meters. start searching for nearby places } }
The above method will be called each time the location manager updates with it’s new value. However, you can see in my if-statement that I’m being quite picky and wanting to get the location correct to the nearest ten meters. That’s pretty tough for the iPhone to do and it could take some time, if it ever gets that close at all. If it doesn’t we’ll never get to a point where we can start searching. Because of this, it’s seriously important that when you tell the location manager to start updating, you also start a timer off that will, after a certain amount of time (10 seconds in my case), just ditch the location manager and do the search anyway using the best location the manager could come up with.
Ok, so we’ve got either a location that’s within 10-meters or thereabouts. How to use this to get the nearby bars, restaurants etc? Well I chose to use the Bing search API. I’m sure Google’s API could do the job too and maybe an update will switch over to Google at some point in the future but Bing’s just seemed a bit more straightforward. For this, I use the NSOperationQueue. When I came to stress-testing and debugging, I was so glad I used this. One example would be that I might fire off a Bing search request for cafes in the area but then, the user might get tired of the wait and just come back to the main screen, check the About screen or just come out of the application. If they did that, the search would still be happening in the background and it’s complete events would be fired off even though we’re not interested in them any more. Dealing with this normally is obviously possible, but a bit messy. However, if you put functionality like this in an NSOperation and use NSOperationQueue to run it, you can automatically cancel individual or all of the operations in that queue with one line of code.
For information about using NSOperation and web services, check out my post on how Bit.ly was used. This post goes into greater detail about the implementation of web services and although it’s a different operation, the principal execution is the same.
Sending Text Messages And E-Mail
So, the application has found the user’s location and the user has selected from a list, the location they’ll be meeting in. With all this data collated, I build a string up that will be sent to their friend but how to actually utilise in-app e-mail and SMS to send the thing? Well, there’s two libraries in the iOS environment which let you do this. One, “MFMessageComposeViewController” allows you to send SMS messages. The other which handles e-mail is “MFMailComposeViewController”. They’re both very similar in usage. You create an instance of the controller, set the delegate, set the recipients as an array, set content and/or body and then display it. Here’s the code When and Where? executes if the user picked a friend’s phone number…
MFMessageComposeViewController *smsComposeController = [[[MFMessageComposeViewController alloc] init] autorelease]; smsComposeController.body = userMessage; smsComposeController.recipients = [NSArray arrayWithObject:[selectedDetails objectForKey:kMeetingDetailContact]]; smsComposeController.messageComposeDelegate = self; [self presentModalViewController:smsComposeController animated:YES];
This is a direct copy-paste from my code so some variables are obviously missing. The interesting part is the last line… The panels which take over the screen when one of these controllers are displayed are called “Modal View Controllers”. The fact they take over the entire screen is what makes them “modal” and this is the approach that is happening in many apps, not just for messaging components, but also things like settings panels. Notable pieces of code above may be the use of the “kMeetingDetailContact” constant. Basically, a dictionary exists in this class which contains all the details a user has chosen (friend name, e-mail or phone number etc). Using a constant just makes sure I don’t make any typing errors. Also, you can see the MFMessageComposeViewController requires a delegate. This particular controller only includes one delegate method, “– messageComposeViewController:didFinishWithResult:” which will be called when the user has tapped “Send” or “Cancel”. In my code, I just dismiss the modal view and display an alert confirming the send.
Detecting No SMS On The iPod
The whole time I was developing this app, I was testing it on my iPhone 4 and my old iPhone 3GS (I purposely didn’t update my 3GS’s firmware so I could test my app on a device running an outdated iOS version). Everything was cool but then, all of a sudden, I thought about what would happen if the app was being run on an iPod or iPad. These devices don’t support SMS so what can I do? Luckily, the “MFMessageComposeViewController” class contains a static method called “canSendText”. If it returns false, the app knows it’s on a device that can’t send a text and so, the address book picker doesn’t display any phone numbers. An easy bit of code to add, but it’s a good example of how you really have to think outside the box sometimes and take into account just how many different types of device your app may run on and what circumstances the person may be running it in.
And That’s That
Well, the app is done and I’ve a few ideas for future versions but the main aim has always been to keep it simple. I use the app myself now and can see the merits of just 3 screens which can be tapped quickly whilst I’m standing in a bar with a pint and only one hand free. Consider your audience when you’re making your app and remember that the iPhone itself is all about ease of use and core functionality so don’t bloat it with anything it really doesn’t need. Thanks for taking the time to read and if you have any requests for any other info I haven’t mentioned, drop a comment below and I’ll update.
Integrating Bit.ly In iPhone Applications
Bit.ly is a wicked service which, if you don’t know, shortens any query-heavy URLs you might have into new URLs of about 11 characters. This came in massively handy when I was developing “When And Where?”, an iPhone application that, at one point, wanted to send a custom Google maps URL via SMS to a user. Without shortening it, the text message would have spanned a good few texts, costing the user a fortune!
Enter the Bit.ly API. So I knew it was the weapon of choice for this task, just one question remained; can it return reponses in JSON? Thankfully it can and it’s not so difficult. A quick class extending NSOperation and it was sorted. Here’s how it was created…
First Off, Using JSON In Cocoa Touch
So the Bit.ly service can return it’s data in the JSON format which is great. JSON is lightweight which is important when our net connection may only be a cellular GPS one. However, there’s no parser for JSON included in the Cocoa Touch library. Luckily, there’s an awesome JSON library called TouchJSON which I’ll be using in this tutorial so go ahead and download it and add the group to your project.
Creating The Objective-C Operation Class
Ok, we’re going to be using NSOperationQueue to fire off our commands. Creating operations for this type of thing is nice for a number of reasons but my favourite is that it can be cancelled mid-way through at any point. When using NSOperationQueue, any operations you will add to the queue will subclass the NSOperation class which is what I’m going to do next in the definition file for our Bit.ly operation which I imaginatively call “BitlyShortenerOperation.h”…
#import #define kBitlyUrlCreatedNotification @"BitlyUrlCreatedNotification" @interface BitlyShortenerOperation : NSOperation { NSString *longURL; NSString *shortURL; } @property (nonatomic, retain) NSString *longURL; @property (nonatomic, retain) NSString *shortURL; - (id) initWithLongURL:(NSString*)originalURL; @end
So the key things our interface is defining is extending NSOperation, defining an NSString called shortURL which will be populated with the result of the bit.ly service, another NSString called longURL which will be populated in the init method with the original URL and lastly, the aforementioned method that will init the class along with the long URL we want shortened. One other thing that maybe isn’t apparent just yet is the creation of the “kBitlyUrlCreatedNotification” constant. Basically we’re going to use this to post a notification which our main class can pick up on so it knows when the operation has completed and the shortened URL is ready.
Ok so the easy part is out of the way. Before we get into the implementation, you should register yourself for the Bit.ly API as you’re going to need a username and API key to use the service. All signed up? Ok, let’s take a look at the implementation file (“BitlyShortenerOperation.m”)
#import "BitlyShortenerOperation.h" #import "CJSONDeserializer.h" @implementation BitlyShortenerOperation @synthesize longURL, shortURL; - (id) initWithLongURL:(NSString*)originalURL { if (self = [super init]) { longURL = originalURL; } return self; } - (void) main { // Construct our bit.ly service url with the username, key and longURL we specified in the init method NSString *apiKey = @"[YOUR API KEY]"; NSString *apiUsername = @"[YOUR API USERNAME]"; NSString *fetchUrlString = [NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apiKey=%@&longUrl=%@&format=json", apiUsername, apiKey, longURL]; // create an NSURL of the service string and define an encoding string object to use in the call NSURL *fetchUrl = [NSURL URLWithString:fetchUrlString]; NSStringEncoding encoding; // here's where the call to the service is actually made NSString *jsonString = [NSString stringWithContentsOfURL:fetchUrl usedEncoding:&encoding error:nil]; // grab the json result from the service call above NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding]; // create a usable dictionary containing the result of the service call by using TouchJSON NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil]; // data response is the top level in the bit.ly json response NSDictionary *dataResponse = [dictionary objectForKey:@"data"]; // grab the shortened url from the service response shortURL = [dataResponse objectForKey:@"url"]; // here, we've posting the 'kBitlyUrlCreatedNotification' notification. other classes can listen out for this and be informed when the short url is ready [self performSelectorOnMainThread:@selector(postNotification:) withObject:[NSNotification notificationWithName:kBitlyUrlCreatedNotification object:nil] waitUntilDone:YES]; } @end
Ok, broken down, it isn’t that complicated really. One thing to note is that the method name “- (void) main” isn’t an arbitrary method name I’ve come up with. It’s a delegate method defined in NSOperation and will automatically be called when the class is added to an NSOperationQueue which will actually call it and that’s exactly what we’re about to do. I mentioned it previously when I defined the header file but if you’re an Actionscript developer, the slightly-scary-looking last line is basically like dispatching an event in AS3 except that any class anywhere can pick up on it as long as it’s subscribed.
Right, now to actually use this code… First thing is that our class that will utilize this wants to subscribe to the “kBitlyUrlCreatedNotification” notification. Then we’ll create an instance of the BitlyShortenerOperation we just created, add it to an NSOperation queue and implement our method that will be called when it’s all done…
// have this class listen out for the 'kBitlyUrlCreatedNotification' notification which will fire the 'bitlyUrlWasCreated' method [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bitlyUrlWasCreated:) name:kBitlyUrlCreatedNotification object:nil]; // create the bitly operation. remember to define 'bitlyOperation' as an instance variable in your .h file so we can access it later bitlyOperation = [[BitlyShortenerOperation alloc] initWithLongURL:@"http://www.google.com"]; // create an operation queue to add it to NSOperationQueue *operationQueue = [[NSOperation alloc] init]; // add the bitly operation to the queue [operationQueue addOperation:bitlyOperation];
Ok the bitlyOperation is now running at this point and will attempt to hit this class’ “bitlyUrlWasCreated” method when it’s done. Let’s define it…
- (void)bitlyUrlWasCreated:(NSNotification *)notification { // you can now access the shortened url as follows... NSLog(@"Bit.ly returned shortened URL: %@", bitlyOperation.shortURL); }
Phew! That’s about it. To keep things easy to read and the code amount down, I’ve omitted all the memory management stuff and none of my variables are being releasing as they should be so be sure to add these in your project. Other than that, this should give you a good starting point as to being in a situation where you can use any web services after a quick Google search and a skim through the service API’s documentation. Good luck and feel free to drop any questions you have into the comments box below.
Using Categories In Objective-C
As an Actionscript developer, it’s the new language features in Objective-C that interest me the most about iPhone development. One feature I’m loving is something called categories.
Essentially, categories allow the programmer to add additional methods to an already-existing class without subclassing it. When coding, these newly created methods are available on the existing object already and as a result, these new methods can be called on instances of that object type.
An Actionscript developer may typically create these types of methods in a separate file declared as static functions. One major difference is that the methods have to be referred to on the class where they were declared. For example, here’s a couple of functions that convert radians to degrees and vice versa…
public static function degreesToRadians(degrees : Number) : Number { return degrees * (Math.PI / 180); } public static function radiansToDegrees(radians : Number) : Number { return radians * (180 / Math.PI); }
So we would typically put these in a separate class (let’s call it MathUtils) and when we want to use them, call MathUtils.degreesToRadians(180). Now, let’s look at how this could be implemented in Objective-C using a custom category…
NSNumber+MathUtils.h
#import <Foundation/Foundation.h> @interface NSNumber (MathUtilities) - (float) toRadians; - (float) toDegrees; @end
NSNumber+MathUtils.m
#import "NSNumber+MathUtils.h" @implementation NSNumber (MathUtilities) - (float) toRadians { return [self floatValue] * (M_PI / 180); } - (float) toDegrees { return [self floatValue] * (180 / M_PI); } @end
The key things here are that when we are defining the interface type on the second line of our interface, we’re defining it’s the already-existing type “NSNumber”. You’ll notice the “(MathUtilities)” after this declaration; this is purely an arbitrary identifier. The only other thing are the two method definitions for converting to radians and degrees.
In the implementation (.m) file, we define the functions that will convert to radians and degrees. However, the main thing here is the use of “self”. Because this is a category and is sitting on top of any NSNumber instances you create, “self” actually refers to the object it’s called on. Here’s an example of it in use…
NSNumber *myDegrees = [NSNumber numberWithFloat:180]; NSLog(@"Radians: %.2f", [myDegrees toRadians]);
We have an NSNumber and then in the NSLog line, we can just call “toRadians” on that object. Now this is a pretty straightforward example. More useful categories would be things like shuffling an array etc. I find it nice to work with although it’s a bit difficult to pick up some code and actually know what categories have been created and are available. Still though, it’s a cool feature…
Archiving Objects With NSCoder
When starting out with external data in iPhone projects, I think most programmers’ first port of call will be the plist format. It’s brilliant; data is stored in it’s native format and when loaded (which is ridiculously easy), it comes in in the same format it was created. However, the formats you can use for data in a plist are restricted. Also, if you have one with a deep hierarchy, loading, updating and saving them not only becomes complex, but also takes longer to process.
Up steps archiving. It’s fast, flexible and is tied into your model so there’s no need to keep referring to plist’s to make sure you’re parsing at the right level and no hard-to-track bugs when your model changes. It also allows data to be saved and loaded in any format so it’s great for saving out entire value objects in their correct format.
Continue Reading
Speaking At LFPUG
Last night I gave a presentation at LFPUG on “Contracting In London”. It was mainly about recommended routes into the contracting lifestyle as well as some tips and tricks to get the most out of things.
It was my first attempt at public speaking and it went down… ok. Seriously though, there was good feedback at the end and I’m pretty proud I made the step.
Video and presentation notes available: here.
