Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

CHAPTER 18: Where Am I? Finding Your Way with Core Location

639

Figure 18–2. The location manager access must be approved by the user.

If the user taps the Don’t Allow button, your delegate will be notified of the fact by the location manager using the locationManager:didFailWithError: with an error code of kCLErrorDenied. At the time of this writing, the only other error code supported by the location manager is kCLErrorLocationUnknown, which indicates that Core Location was unable to determine the location but that it will keep trying. The kCLErrorDenied error generally indicates that your application will not be able to access Core Location any time during the remainder of the current session. On the other hand, kCLErrorLocationUnknown errors indicate a problem that may be temporary.

NOTE: When working in the simulator, a dialog will appear outside the simulator window, asking to use your current location. In that case, your location will be determined using a super-secret

algorithm kept in a locked vault buried deep beneath Apple headquarters in Cupertino.

Trying Out Core Location

Let’s build a small application to detect the iPhone’s current location and the total distance traveled while the program has been running. You can see what our final application will look like in Figure 18–3.

www.it-ebooks.info

640

CHAPTER 18: Where Am I? Finding Your Way with Core Location

Figure 18–3. The WhereAmI application in action. This screenshot was taken in the simulator. Notice that the vertical accuracy is a negative number, which tells us it couldn’t determine the altitude.

In Xcode, create a new project using the Single View Application template, call the project WhereAmI, and set Device Family to iPhone. Select BIDViewController.h, and make the following changes:

#import <UIKit/UIKit.h>

#import <CoreLocation/CoreLocation.h>

@interface BIDViewController :

UIViewController <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager; @property (strong, nonatomic) CLLocation *startingPoint; @property (strong, nonatomic) IBOutlet UILabel *latitudeLabel; @property (strong, nonatomic) IBOutlet UILabel *longitudeLabel;

@property (strong, nonatomic) IBOutlet UILabel *horizontalAccuracyLabel; @property (strong, nonatomic) IBOutlet UILabel *altitudeLabel;

@property (strong, nonatomic) IBOutlet UILabel *verticalAccuracyLabel; @property (strong, nonatomic) IBOutlet UILabel *distanceTraveledLabel;

@end

First, notice that we’ve included the Core Location header files. Core Location is not part of either UIKit or Foundation, so we need to include the header files manually. Next, we

www.it-ebooks.info

CHAPTER 18: Where Am I? Finding Your Way with Core Location

641

conform this class to the CLLocationManagerDelegate method so that we can receive location information from the location manager.

After that, we declare a CLLocationManager pointer, which will be used to hold the instance of the Core Location we create. We also declare a pointer to a CLLocation, which we will set to the location we receive in the first update from the location manager. This way, if the user has our program running and moves far enough to trigger updates, we’ll be able to calculate how far our user moved. Our delegate will be notified of the previous location with each call, but not the original starting location, which is why we store it.

The remaining properties are all outlets that will be used to update labels on the user interface.

Select BIDViewController.xib to create the GUI. Using Figure 18–3 as your guide, drag 12 Labels from the library to the View window. Six of them should be placed on the left side of the screen, right-justified, and made bold. Give the six bold labels the values

Latitude:, Longitude:, Horizontal Accuracy:, Altitude:, Vertical Accuracy:, and Distance Traveled:. Since the Horizontal Accuracy: label is the longest, you might place that one first, and then option-drag out copies of that label to create the other five left-side labels. The six right-side labels should be left-justified and placed next to each of the bold labels.

Each of the labels on the right side should be connected to the appropriate outlet we defined in the header file earlier. Once you have all six attached to outlets, double-click each one in turn, and delete the text it holds.

Save your changes. Next, return to Xcode, select BIDViewController.m, and make the following changes at the top of the file:

#import "BIDViewController.h"

@implementation BIDViewController

@synthesize locationManager; @synthesize startingPoint; @synthesize latitudeLabel; @synthesize longitudeLabel; @synthesize horizontalAccuracyLabel; @synthesize altitudeLabel; @synthesize verticalAccuracyLabel; @synthesize distanceTraveledLabel;

.

.

.

Insert the following lines in viewDidLoad to configure the location manager:

- (void)viewDidLoad { [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib. self.locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self;

locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation];

www.it-ebooks.info

642

CHAPTER 18: Where Am I? Finding Your Way with Core Location

}

Insert the following lines in viewDidUnload to clean up our outlets:

- (void)viewDidUnload { [super viewDidUnload];

//Release any retained subviews of the main view.

//e.g. self.myOutlet = nil;

self.locationManager = nil; self.latitudeLabel = nil; self.longitudeLabel = nil; self.horizontalAccuracyLabel = nil; self.altitudeLabel = nil; self.verticalAccuracyLabel = nil; self.distanceTraveledLabel= nil;

}

And insert the following new methods at the end of the file:

.

.

.

#pragma mark -

#pragma mark CLLocationManagerDelegate Methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

if (startingPoint == nil) self.startingPoint = newLocation;

NSString *latitudeString = [NSString stringWithFormat:@"%g\u00B0", newLocation.coordinate.latitude];

latitudeLabel.text = latitudeString;

NSString *longitudeString = [NSString stringWithFormat:@"%g\u00B0", newLocation.coordinate.longitude];

longitudeLabel.text = longitudeString;

NSString *horizontalAccuracyString = [NSString stringWithFormat:@"%gm", newLocation.horizontalAccuracy];

horizontalAccuracyLabel.text = horizontalAccuracyString;

NSString *altitudeString = [NSString stringWithFormat:@"%gm", newLocation.altitude];

altitudeLabel.text = altitudeString;

NSString *verticalAccuracyString = [NSString stringWithFormat:@"%gm", newLocation.verticalAccuracy];

verticalAccuracyLabel.text = verticalAccuracyString;

CLLocationDistance distance = [newLocation distanceFromLocation:startingPoint];

NSString *distanceString = [NSString stringWithFormat:@"%gm", distance]; distanceTraveledLabel.text = distanceString;

}

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]