Code Example to add location services to your iPhone iOS app (iOS7)

This will introduce you to the very basics of CoreLocation services and getting the location of the device currently being used.

About CoreLocation
The Core Location framework lets you determine the current location or heading associated with a device. The framework uses the available hardware to determine the user’s position and heading. You use the classes and protocols in this framework to configure and schedule the delivery of location and heading events. You can also use it to define geographic regions and monitor when the user crosses the boundaries of those regions.

Now to the code…

The set up

First you will need to create a project start by opening up XCode and selecting a Single View Application.
xcode

Name the project and continue.

Adding Location Frameworks

The first step to adding location services to your application is to add the CoreLocation framework.
1. Select your target and go to the “Build Phases” tab.
lib files
2. Click the “+” button under “Link Binary With Libraries”
3. Select the CoreLocation framework and click “Add”
lib files

The code

Now you’ll need to create an instance of CLLocationManager. There is usually one instance of this per app so a good place for this is in the Appication Delegate and then each view can access the current location from the App Delegate.

To start, open your App Delegate header file (.h):

Add

#import <CoreLocation/CoreLocation.h>

Then on the interface line add CLLocationManagerDelegate

@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

Lastly add a property called locationManger.

@property (strong, nonatomic) CLLocationManager *locationManager;

Now in the Application Delegate Implementation (.m) add a new method that is part of the CLLocationManagerDelegate

First lets create The Location Manager Object.

    if(self.locationManager == nil){
        // Override point for customization after application launch.
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 500;
        
        self.locationManager = _locationManager;
    }

To add a description or purpose as to why you need the location you should do it in the properties list file. Open your Info.plist and add NSLocationUsageDescription as a new entry then set the string to what ever you want. It gives you a chance to explain what your app is going to do with their location information.
(NOTE: this use to be called purpose in older versions of iOS but they have since moved it since version 6).

Lets talk about what this does:
.desiredAccuracy – The desired accuracy property allows you to tell the device how accurate you would like the location information to be. This should be set based on your application’s needs. Don’t set this property to kCLLocationAccuracyBest if you only need to know what city they are in. NOTE: This is the “desired” accuracy, it is not guaranteed. The device will determine the best available information and provide it to you but you are not, however, guaranteed any level of accuracy.

.distanceFilter – The distance filter property tells the location manager how far a device needs to move (horizontally vs. an altitude change) before triggering a new location event. It is measured in meters. You can set the property to kCLDistanceFilterNone to be notified of all events (this is also the default value).

Starting location services
To start the services up add this line after we set up our location manager above and before the return YES;

// start the service
if([CLLocationManager locationServicesEnabled]){
    [self.locationManager startUpdatingLocation];
}

(NOTE: If location services are not enabled and you start updating location services, the user will be prompted to enable location services. This could be annoying to the end user if they have to answer “No” every time your app launches.)

Receiving location changes
We’ve started location services, but now we need to start receiving updates to location changes. This is all done through the CLLocationManagerDelegate protocol. There are a number of available methods to implement for this delegate but the three most important are probably:

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status;

But we will only focus on the first one.

One of the first things you should do is check the timestamp of the latest location detected. When you first start updating location services, the location manager will receive the last known location of the device, this could be hours or days old depending on the last time location services were used. This following code will only use a location that has been found in the last 15.0 seconds.

The next check to perform is to see how accurate the latest location is. This can be done by looking at the .horizontalAccuracy property. This property tells you how accurate your location information is. As I stated above, you can request to have very accurate locations but you are not guaranteed it.

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *myLocation = [locations lastObject];
    
    NSDate* eventDate = myLocation.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    if (abs(howRecent) < 15.0)
    {
        //Location timestamp is within the last 15.0 seconds, let's use it!
        if(myLocation.horizontalAccuracy < 35.0){
            //Location seems pretty accurate, let's use it!
            NSLog(@"latitude %+.6f, longitude %+.6f\n",
                  myLocation.coordinate.latitude,
                  myLocation.coordinate.longitude);
            NSLog(@"Horizontal Accuracy:%f", myLocation.horizontalAccuracy);
            
            //Optional: turn off location services once we've gotten a good location
            [manager stopUpdatingLocation];
            
            
        }
    }
    
}

Your application's need will determine how accurate of a location you need. Again, if you just need the city the user is in, you won't need it to be as accurate as if you were trying to find something within walking distance. In the code above, I have set my accuracy threshold to 35.0 meters.

The code above will print the new location to the console and then turn off location services. This is an optional step but if you don't need location services anymore, it's a smart thing to turn them off to conserve your user's battery.

Full Code

Loading Facebook Comments ...