Thursday, October 8, 2009

Asynchronous Tasks in your iPhone App

One thing that as made web applications much easier to use in the last few years is the integration of Ajax into web pages. Before that, each click of the user would block the application until the next page loads... not really a great user experience.

Now when you want to trigger a long task in the background, you can use Javascript to trigger asynchronous requests... that is just great!

Well in standard applications design, it is also very handy to be able to do such thing, and we usually do it using threads. The iPhone platform obviously provides everything you need to perform that, and that's pretty simple! Just awesome! Here is how it works...

The documentation you want to read is the NSOperation Class it provides the tools to trigger a task in the background. And as the documentation says, you will most of the time want to manage a queue of operations rather than just a single operation. So the best thing to do (in my opinion) is to create a Manager (singleton) which owns a queue of operations: NSOperationQueue Class.

This way you can add operations to the queue, and they will all be treated in order. A good example of this kind of manager is the ConnectionManager of the ObjectiveResource library.

You can use it this way:

- (void)fileDownloaded: (NSData *)data {
    // Do stuff here
}
- (void)downloadFile: (NSUrl *)url {
    // Download file here

    [self performSelectorOnMainThread: @selector(fileDownloaded:)
                           withObject: downloadedData
                        waitUntilDone: YES];
}

And somewhere in your code trigger the asynchronous download:

[[ConnectionManager sharedInstance] runJob: @selector(downloadFile:)
                                  onTarget: self
                              withArgument: url];

That's it! So when you call runJob on the connection manager, it queues the job in the operation queue... so if you need to download ten files, they will be processed asynchronously one-by-one while the user is still using your app, without interruption.

Hope this was helpful!

No comments:

Post a Comment