Easy Background Tasks

So if you’ve read up on Executing Code in the Background under iOS 4 at all, you’ve probably looked at the recommended design patterns

  • Wrap any long-running critical tasks with beginBackgroundTaskWithExpirationHandler: and endBackgroundTask: calls. This protects those tasks in situations where your application is suddenly moved to the background.
  • Wait for your application delegate’s applicationDidEnterBackground: method to be called and start one or more tasks then.

and thought “Sheesh, how about the JUST KEEP GOING design pattern?” Like, for instance, if you’re somewhere in the middle of downloading 120 meg of IAP content, with code that’s been working since 3.0. Seems like it’s unduly difficult to just go ahead and do that, right?

Well, actually, no. It’s quite easy. Trivial to the point of embarrassment, in fact. Here’s the scoop:

Easy background Tasks in iOS 4

Seriously, like 10 lines of code in applicationDidEnterBackground: to call beginBackgroundTaskWithExpirationHandler: and four more where you regularly clean up after your job completes whilst in the foreground to call endBackgroundTask:, and you’re done, background multitasking works, yippee!

We added another handful of lines in our progress handler to wind down more cleanly when time’s running out, but you probably don’t even have to do that. Much easier than you thought it’d be to get all up in the background, isn’t that now?

h/t: iOS Development Goodies!

Alex | September 19, 2010

Leave a Reply