Difference between revisions of "An Example iOS 7 Location Application"

From Techotopia
Jump to: navigation, search
m (Text replacement - "<!-- Ezoic - BottomOfPage - bottom_of_page --> <div id="ezoic-pub-ad-placeholder-114"></div> <!-- End Ezoic - BottomOfPage - bottom_of_page -->" to "<htmlet>ezoicbottom</htmlet>")
m (Text replacement - "<htmlet>ezoicbottom</htmlet>" to "")
Line 168: Line 168:
  
  
<htmlet>ezoicbottom</htmlet>
+
 
 
<hr>
 
<hr>
 
<table border="0" cellspacing="0">
 
<table border="0" cellspacing="0">

Revision as of 18:03, 11 May 2016

PreviousTable of ContentsNext
Getting Location Information using the iOS 7 Core Location FrameworkWorking with Maps on iOS 7 with MapKit and the MKMapView Class


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


Having covered the basics of location management in iOS 7 applications in the previous chapter it is now time to put theory into practice and work step-by-step through an example application. The objective of this chapter is to create a simple iOS application that tracks the latitude, longitude and altitude of an iOS device. In addition, the level of location accuracy will be reported, together with the distance between a selected location and the current location of the device.


Contents


Creating the Example iOS 7 Location Project

The first step, as always, is to launch the Xcode environment and start a new project to contain the location application. Once Xcode is running, select the File -> New -> Project… menu option and configure a new iOS iPhone or iPad application named Location with a matching class prefix using the Single View Application template.

Designing the User Interface

The user interface for this example location app is going to consist of a number of labels and a button that will be connected to an action method. Initiate the user interface design process by selecting the Main.storyboard file. Once the view has loaded into the Interface Builder editing environment, create a user interface that resembles as closely as possible the view illustrated in Figure 69-1.

In the case of the five labels in the right hand column which will display location and accuracy data, make sure that the labels are stretched to the right until the blue margin guideline appears. The data will be displayed to multiple levels of decimal points requiring space beyond the default size of the label.

Select the label object to the right of the “Current Latitude” label in the view canvas, display the Assistant Editor panel and verify that the editor is displaying the contents of the LocationViewController.h file. Ctrl-click on the same Label object and drag to a position just below the @interface line in the Assistant Editor. Release the line and in the resulting connection dialog establish an outlet connection named latitude. Repeat these steps for the remaining labels, connecting then to properties named longitude, horizontalAccuracy, altitude, verticalAccuracy and distance respectively.


The user interface layout for an iOS 7 location example app

Figure 69-1


The final step of the user interface design process is to connect the button object to an action method. Ctrl-click on the button object and drag the line to the area immediately beneath the newly created outlets in the Assistant Editor panel. Release the line and, within the resulting connection dialog, establish an Action method on the Touch Up Inside event configured to call a method named resetDistance.

Select the LocationViewController.h file, verify that the outlets are configured correctly and add a property in which to store the start location coordinates and the location manager object. Now is also an opportune time to import the <CoreLocation/CoreLocation.h> header file and to declare the class as implementing the CLLocationManagerDelegate protocol:

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface LocationViewController : UIViewController
     <CLLocationManagerDelegate>

@property (strong, nonatomic) IBOutlet UILabel *latitude;
@property (strong, nonatomic) IBOutlet UILabel *longitude;
@property (strong, nonatomic) IBOutlet UILabel *horizontalAccuracy;
@property (strong, nonatomic) IBOutlet UILabel *altitude;
@property (strong, nonatomic) IBOutlet UILabel *verticalAccuracy;
@property (strong, nonatomic) IBOutlet UILabel *distance;

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *startLocation;
- (IBAction)resetDistance:(id)sender;
@end

Creating the CLLocationManager Object

The next task is to implement the code to create an instance of the CLLocationManager class. Since this needs to occur when the view loads, an ideal location is in the view controller’s viewDidLoad method in the LocationViewController.m file:

- (void)viewDidLoad {
    [super viewDidLoad];
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
    _startLocation = nil;
}

The above code creates a new CLLocationManager object instance and configures it to use the “best accuracy” setting. It then declares itself as the application delegate for the object. The location manager object is then instructed to begin updating location information via a call to the startUpdatingLocation method. Since location tracking has just begun at this point, the startLocation object is also set to nil.

Implementing the Action Method

The button object in the user interface is connected to the resetDistance action method so the next task is to implement that action. All this method needs to do is set the startlocation object to nil:

-(void)resetDistance:(id)sender
{
        _startLocation = nil;
}

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Implementing the Application Delegate Methods

When the location manager detects a location change, it calls the didUpdateToLocation delegate method. Since the view controller was declared as the delegate for the location manager in the viewDidLoad method, it is necessary to now implement this method in the LocationViewController.m file:

#pragma mark -
#pragma mark CLLocationManagerDelegate

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
                  fromLocation:(CLLocation *)oldLocation
{
     NSString *currentLatitude = [[NSString alloc] 
                  initWithFormat:@"%+.6f", 
                  newLocation.coordinate.latitude];
     _latitude.text = currentLatitude;

     NSString *currentLongitude = [[NSString alloc] 
          initWithFormat:@"%+.6f",
          newLocation.coordinate.longitude];
     _longitude.text = currentLongitude;

     NSString *currentHorizontalAccuracy = 
              [[NSString alloc] 
             initWithFormat:@"%+.6f",
             newLocation.horizontalAccuracy];
     _horizontalAccuracy.text = currentHorizontalAccuracy;

     NSString *currentAltitude = [[NSString alloc] 
                  initWithFormat:@"%+.6f",                                                          
                  newLocation.altitude];
     _altitude.text = currentAltitude;

     NSString *currentVerticalAccuracy = 
              [[NSString alloc] 
              initWithFormat:@"%+.6f",
              newLocation.verticalAccuracy];
     _verticalAccuracy.text = currentVerticalAccuracy;

     if (_startLocation == nil)
            _startLocation = newLocation;
       
     CLLocationDistance distanceBetween = [newLocation
            distanceFromLocation:_startLocation];

     NSString *tripString = [[NSString alloc] 
           initWithFormat:@"%f", 
           distanceBetween];
     _distance.text = tripString;
}

Despite the apparent length of the method it actually performs some very simple tasks. To begin with, it extracts location and accuracy information from the newLocation CLLocation object passed through to the method as an argument. In each case, it creates an NSString object containing the extracted value and displays it on the corresponding user interface label.

If this is the first time that the method has been called either since the application was launched or the user pressed the Reset Distance button, the locationDistance object is set to the current location. The distanceFromLocation method of the newLocation object is then called, passing through the locationDistance object as an argument in order to calculate the distance between the two points. The result is then displayed on the distance label in the user interface.

The didFailWithError delegate method is called when an error is encountered by the location manager instance. This method should also, therefore, be implemented:

-(void)locationManager:(CLLocationManager *)manager 
didFailWithError:(NSError *)error
{
}

The action taken within this method is largely up to the application developer. The method, might, for example, simply display an alert to notify the user of the error.

Building and Running the Location Application

Click on the Run button located in the Xcode project window toolbar. Once the application has compiled and linked it will launch into the iOS Simulator. Before location information can be gathered, the user is prompted to grant permission. Once permission is granted, the application will begin tracking location information. By default, the iOS Simulator will be configured to have no current location causing the labels to remain unchanged. In order to simulate a location, select the iOS Simulator Debug -> Location menu option and select either one of the pre-defined locations or journeys (such as City Bicycle Ride), or Custom Location… to enter a specific latitude and longitude. The following figure shows the application running in the iOS Simulator after the Apple location has been selected from the menu:


An Example iOS 7 Location based application running

Figure 69-2


To experience the full functionality of the application it will be necessary to install it on a physical iOS device, a process that is outlined in the chapter entitled Testing Apps on iOS 7 Devices with Xcode 5. Once the application is running on the device, location data will update as you change location.

One final point to note is that the distance data relates to the distance between two points, not the distance travelled. For example, if the device accompanies the user on a 10 mile trip that returns to the start location the distance will be displayed as 0 (since the start and end points are the same).


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Getting Location Information using the iOS 7 Core Location FrameworkWorking with Maps on iOS 7 with MapKit and the MKMapView Class