Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Monday, December 16, 2013

Run On a Background Thread in iOS

So you have some code that you want to run outside of the main thread in the background, eh?

Any long-running process, but especially those where you're connected to a remote server, will need to run in the background so as not to interfere with the user experience. The main thread needs to be left alone to handle things such as drawing the screen for the user and allowing user input, so how do we gin-up a background thread to handle our long-running processes?

  dispatch_queue_t backgroundProcessQueue = dispatch_queue_create("", 0);
  dispatch_async(backgroundProcessQueue, ^{
    NSString *requestURL = @"";
    // Obligatory hand-wavy-remote-fetch
    NSDictionary *response = [FetchMasterGeneral runRemoteRequestAndGetResponse:requestURL];
    dispatch_async(dispatch_get_main_queue(), ^{
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"We're Back!" message:@"Whew! Sorry that took so long." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
      [alert show];

Bam, easy! Now you may want to display a wait message while you're running this background process (maybe not), and if you're interested in using one, I personally use the SVProgressHud plugin everywhere I run a background thread.

Best of luck on your adventure!

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates:

Popular Posts

Designed By Seo Blogger Templates