iOS Multitasking: Background Tasks

iOS Multitasking: Background Tasks

Tutorial Details
  • Technology: Beginner
  • Difficulty: Intermediate
  • Estimated Completion Time: 5-10 minutes
This entry is part 3 of 4 in the series iOS Multitasking

This is the third part in the iOS Multitasking Series. Compared to Local Notifications, Background Audio, Background Location, and VOIP (Not covered in this series), Background Tasks and Fast App Switching are the easiest to implement. For this tutorial, you will need to understand blocks.

Step 1: Creating the Project

For the simplicity of this tutorial, create a window based application so we do not have to deal with View Controllers and extras (same implementation is used no matter what template you use). Name it Background Task and uncheck “Use Core Data” and “Include Unit Tests”.

iOS_Background_Tasks

Then open up the Background_TasksAppDelegate.m.

Step 2: Implementing the code

Now scroll down to the applicationDidEnterBackground: method and add the following code:

	if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
		if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
			UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
			__block UIBackgroundTaskIdentifier background_task; //Create a task object
			background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
				[application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
				background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
				//System will be shutting down the app at any point in time now
			}];
			//Background tasks require you to use asyncrous tasks
			dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
				//Perform your tasks that your application requires
				NSLog(@"\n\nRunning in the background!\n\n");
				[application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
				background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
			});
		}
	}

Wrap Up

As you can see, Background Tasks are extremely short and easy to implement. If you have any need for help or just want to post a suggesion, then comment below!

Series Navigation«iOS Multitasking: Background AudioiOS Multitasking: Background Location»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Willy B

    hi,

    I see on the app store some apps which have continuous background using GPS location every 10 minutes, that’s to say, they have new background task every 10 minutes… How can they do that? Could you help me to achieve it? Thanks so much…

  • Jack Abeel
    Author

    That is a different subject by itself. I will be covering that in the series.

    • Wiily B

      Hi Jack,

      If you’re able to achieve it (to get news tasks every 10 minutes), we can make a deal.

      Answer me to this e-mail: “aunkenoloaceptes@yahoo.es” and we can talk about it.

      Thanks a lot,

      Willy B.

  • umakanta

    I understood what is happening.
    I don’t know why you wrote that.

    Is it a format to execute background task ?

    Can you give details of each lines of code, which is written in applicationDidEnterBackground function.

  • Developer

    HI, i have one doubt about this background task is it going to be closed your application after 10 min. because iOs will not allow you to create an application which is working 24*7 in background mode. but i want to implement like this i have used this code for allow background task

    counterTask = [[UIApplication sharedApplication]
    beginBackgroundTaskWithExpirationHandler:^{
    }];
    theTimer=[NSTimer scheduledTimerWithTimeInterval:0.5
    target:self
    selector:@selector(countUp)
    userInfo:nil
    repeats:YES];,/pre>
    here my stuff is i am sending some data at a particular time using NSTimer it all works fine but after 10 min. my application is going to be closed. i am sending user location at some particular time by using method of – (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation,/pre> but this is not working for me do you have any ideas about this.

  • Tyler

    I am trying to get an asynchronous download to complete in background, but am unsure what to put in to complete the task in the background. This tutorial lays the groundwork, but does nothing to show how to add in what you need finished.

  • lakshmi

    Hi ,

    Can I play the audio on background by using the above code. I tried its not working. Can you please suggest me. I am using MPMoviePlayerController to play the audio.I need to play audio in background also.
    I

  • long

    Hi Jack !
    Do it work fine with NSURLconnection ???
    Thanks

  • Will

    Hello,
    I hop my question is easy. I want to add a timer in an app. The app is not doing anything unless I am entering data when its in foreground. When the phone is locked, the timer stops. how do you code so once that timer is initiated, it will run even with the phone locked or the app in background. This timer will never be set for more than 240 seconds. Thanks.

  • Rajneesh

    Hi i want to perform some task periodically when app is minimize….
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
    but did not rum this selector…

  • LittlePeculiar

    working perfectly for needs – Thanks Jack, you’re awesome

  • http://www.facebook.com/hoangdoanh Hoang Doanh

    location. But application keep active state in background task only for 10 minutes. How can I make it run infinitely. How can I talk with you instantly ?

  • kuldeep

    I m using background audio moe in my app and when i pressed home button than navigation bar looks red color … is any issue this red bar to accept my app in itune