iOS Multitasking: Background Location

iOS Multitasking: Background Location

Tutorial Details
  • Technology: iOS SDK
  • Difficulty: Beginner
  • Completion Time: 30 - 45 Minutes
This entry is part 4 of 4 in the series iOS Multitasking

This is the fourth and final part of the series on iOS Multitasking. Today we will be covering Background Location. Just like the previous iOS Multitasking tutorials in this series, this feature is simple and easy to implement. So let’s start!

Step 1: Creating the Project

First, create a project with the View Based Application Template. Name the project BackgroundTracker and turn off Unit Tests.

Background Location

Now, go to the target settings and then go to the Build Phases Tab.

Background Location

In the “Link Binary with Libraries” section add the CoreLocation Framework.

Background Location

Now, under Supporting Files go to BackgroundTrack-Info.plist and add a new line with the key of Required Background Modes. It should become an array. Open the array and for Item 0 set the value for the key to App registers for location updates.

Background Location

Step 2: Coding the User Interface

Now go into the project sidebar and open up the BackgroundTrackerViewController.h. At the top, under #import <UIKit/UIKit.h>, add the following line:

#import <CoreLocation/CoreLocation.h>
 

To the immediate right of the UIViewController subclass declaration add the following line:

 <CLLocationManagerDelegate>
 

Then under the @interface declaration (right under the line you just added to the CLLocationManagerDelegate) add the following code:

 	CLLocationManager *locationManager;
	IBOutlet UIButton *startTrackingButton;
	IBOutlet UILabel  *alertLabel;

Then under the lower closing brace add these lines:

 	@property(nonatomic, retain) CLLocationManager *locationManager;
	@property(nonatomic, retain) IBOutlet UIButton *startTrackingButton;
	@property(nonatomic, retain) IBOutlet UILabel  *alertLabel;
	- (IBAction)startTracking:(id)sender;

Your .h file should like the following.

 	#import &lt;UIKit/UIKit.h&gt;
	#import &lt;CoreLocation/CoreLocation.h&gt;
	@interface BackgroundTrackerViewController : UIViewController &lt;CLLocationManagerDelegate&gt; {
	    CLLocationManager *locationManager;
	    IBOutlet UIButton *startTrackingButton;
	    IBOutlet UILabel  *alertLabel;
	}
	@property (nonatomic, retain) CLLocationManager *locationManager;
	@property (nonatomic, retain) IBOutlet UIButton *startTrackingButton;
	@property (nonatomic, retain) IBOutlet UILabel  *alertLabel;
	- (IBAction)startTracking:(id)sender;
	@end
 

Step 3: Setup the Interface XIB

Now open the BackgroundTrackerViewController.xib. First, drag out a UIButton to the middle of the interface so that the blue guidelines are in a cross shape. Then go the Connections Inspector. Drag the touchUpInside action to the file’s owner and select startTracking:. Then drag the referencing outlet to the file’s owner and select the startTrackingButton. Now drag a UILabel and position it above the UIButton. Set the width to be the the entire screen and set the text to say “Unable to find Location” (without quotes). Then in the Attributes Inspector set the Hidden checkbox to be checked. Then go to the connections inspector. Then drag the referencing outlet to the file’s owner and select alertLabel.

Step 4: Setup the Location Tracker

Now go and open LocationTrackerViewController.m. Under the @implementation line add the following two lines of code:

 	@synthesize startTrackingButton;
	@synthesize locationManager;
	@synthesize alertLabel;

Now in the dealloc: method add the following lines of code under the [super dealloc]; line.

    [locationManager release];
    [startTrackingButton release];
    [alertLabel release];

Now add the following lines of code to the viewDidLoad: under the [super viewDidLoad]; line.

    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    //Only applies when in foreground otherwise it is very significant changes
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

And under the @synthesize declarations add the following method:

- (IBAction)startTracking:(id)sender {
    [locationManager startUpdatingLocation];
}

Then above the startTracking: method add the CLLocatioManager delegate methods (code below).

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    CLLocationCoordinate2D currentCoordinates = newLocation.coordinate;
    [alertLabel setText:@"Location Has been found"];
    [alertLabel setHidden:NO];
    NSLog(@"Entered new Location with the coordinates Latitude: %f Longitude: %f", currentCoordinates.latitude, currentCoordinates.longitude);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Unable to start location manager. Error:%@", [error description]);
    [alertLabel setHidden:NO];
}
 

Wrap Up

Like the previous three, Background Location is extremely easy to implement. If you need any help or just have a helpful tip please comment below.

Series Navigation«iOS Multitasking: Background Tasks

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://twitter.com/inancgumus Inanc Gumus

    Great tutorial.

    Some notes to take for new comers:

    1- You don’t need to define locationManager, … instance variables, just the properties will do fine and automatically define instance variables themselves implicitly

    2- You don’t need to synthesize over and over again. Just with one synthesize and adding commas together will do fine, like: synthesize startTrackingButton, locationManager;

    3- locationManager setDesiredAccuracy:kCLLocationAccuracyBest: Using this can quickly draw processing power and thus battery power from the devices.

    Cheers.

  • bjornst

    Not much of example code these days? Can’t you add the source project for the article for download? That goes for all parts of these tutorials on iOS multitasking. Would be nice to be able to study the source code.

    Thx for good articles tho!

  • Jack Abeel
    Author

    @Inanc Gumus I totally agree with your viewpoint on those shortcuts for new comers. I just use the traditional as a style since I have been working with the SDK since 2.0.

    @bjornst Sorry I could not attach the files to the tutorial, I had some difficulties with dropbox sharing before they were published. Here is the link for the source code for all four tutorials if you wish to have it. iOSMultitasking.zip

  • bjornst

    Thx! perfect!

  • Vijay

    Thanks For Your Article its nice and will help me . Thanks for providing code.

  • Matt Mahesh

    Great article. If you need create surveys to get feedback for your mobile apps, check out http://www.mobosurvey.com they use jquery mobile for their survey generator and it looks great. I am using their service to get feedback for my apps.

  • Michael

    Thank you for the tutorial Jack.

    One question, is it possible to send the location updates to a web server from a background task at user defined regular intervals without the application coming to the foreground?

  • http://twitter.com/jdandrea Joe

    Here’s a question for you: Let’s say your app needs to make updates in the background, based on significant location changes, but it does not need to bring the app to the foreground in order to act upon each change. (In this case, it’s really just rescheduling a Local Notification that is influenced in part by significant location.) Is that doable?

  • hacer

    How can I save these background locations in plist ?

  • 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];

    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
    but this is not working for me do you have any ideas about this.

    • aunkenoloaceptes@yahoo.es

      Hi Developer,

      Write to me: aunkenoloaceptes@yahoo.es , because i’m trying to get the same as you. I can give you some specific information and help each other.

      When you write me, put on the subject: “mobile tuts – Developer”.

      Thanks,

      WillyB

  • Developer

    Hey any body can give me answer for above question?

  • Pradip

    Thanks

  • Dan Thornett

    Thanks for the tutorial Jack,

    Could you offer some advice for developing this app further, I wan’t the app to simply open up upon receiving a local notification based on exiting a region (using region-based location monitoring).
    Could you provide some code that follows this template please ?

    Many thanks :-)

  • iOS Developer

    Hi,
    I am trying to do the same what the @Developer is doing !! Can you help me ?

  • http://www.pgluck.com Peter Gluck

    Thanks for this. My updates were occurring, but not in when the app was in the background. The crucial bit I was missing was:

    [locationManager setDelegate:self]

    Once I added this and implemented CLLocationManagerDelegate:didUpdateToLocation my background updates worked perfectly!

    Regards,

    Peter

  • http://www.pgluck.com Peter Gluck

    @Developer, WillyB, @IOS Developer:

    In Step 1 of the tutorial, the app is configured to perform background location updates. This is one of the few exceptions where iOS permits the app to continue running in the background. No additional effort is required. Here is a great blog article that explains how iOS application management works:

    http://speirs.org/blog/2012/1/2/misconceptions-about-ios-multitasking.html

    Happy coding,

    Peter

  • Joe Plocki

    Thanks for this… I’ve been reading through overly-complicated forum topics for the last hour, that still didn’t do what I needed. This is precisely what I was looking for.

  • DanM

    I need accuracy in the background. Significant changes will not do. Is this possible? What do I need to do to receive frequent updates? Thx! -Dan

  • jkaluzka

    Is there any way to turn on and off location manager in background ? (or maybe in suspended mode, when device is locked ?)

  • Regis

    Where do you see any background task to determine the location in this code and the sample code attached ????

  • Malek

    Where is the background stuff in all of this? I was waiting to see some code in the applicationDidEnterBackground method? I think this post is refering to the background location: http://www.mindsizzlers.com/2011/07/ios-background-location/