ios core location

52
Core Location Finding Your Way With Core Location

Upload: richa-jain

Post on 28-Jun-2015

1.177 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: iOS Core location

Core LocationFinding Your Way With Core Location

Page 2: iOS Core location

Core Location

Core Location framework is used to determine the current latitude and longitude of a device and to configure and schedule the delivery of location-related events.

Core Location uses a type of streaming notification so that your application receives updates as the GPS ascertains a more accurate fix.

Page 3: iOS Core location

There are three technologies that core

location uses : GPS Reads microwave signals from

multiple satellites to determine the current location

Cell Tower Triangulation Determine the current location by

calculation based on location of cell towers in iPhone’s range.

Wi-Fi positioning Service (WPS) Uses IP address from iPhone’s Wi-Fi

connection by referencing database of service providers and areas they service

Page 4: iOS Core location

Location Manager(CLLocationManager)

This class defines the interface for configuring the delivery of location-related events to your application.

To interact with core location we need to create an instance of Location Manager.CLLocationManager *locationManager=[[CLLocationManager alloc]init];

Assign a delegate object to it, and configure the

desired accuracy you want.

Page 5: iOS Core location

Location Object(CLLocation)

Represents the location data generated by a CLLocationManager object.

This object incorporates the geographical coordinates and altitude of the device’s location along with values indicating the accuracy of the measurements and when those measurements were made

Page 6: iOS Core location

Setting Desired Accuracy

The accuracy is set using CLLocationAccuracy

Value, a type that’s defined as double.

kCLLocationAccuracyBest kCLLocationAccuracyNearestTenMeters kCLLocationAccuracyHundredMetres kCLLocationAccuracyKilometers kCLLocationAccuracyThreeKilometers

Setting Delegate and Accuracy:

locationManager.delegate=self;locationManager.desiredAccuracy= kCLLocationAccuracyBest

Page 7: iOS Core location

Setting Distance Filter

By specifying distance filter you can tell Location manager not to notify for every change in location but to only notify you when location changes by certain amount.

Setting up a distance filter reduced the amount of polling that your application does.

Specifying a distance filter of 1000 tells location manager not to notify the delegate until the iPhone has moved at least 1000 meters from previously reported position

Page 8: iOS Core location

For example:

locationManager.distanceFilter=1000.0f;

To return location manager to return to default setting with no filter then:

locationManager.distanceFilter=

kCLDistanceFilternone;

Page 9: iOS Core location

Starting the Location Manager

When you are ready to start polling for location, you tell the location manager to start.

It will continue to call your delegate method whenever it senses a change that exceeds the current distance filter

[locationManager startUpdatingLocation];

Page 10: iOS Core location

Location Manager Delegate

The location manager must confirms to CLLocationManagerDelegate protocol, which defines two methods, both are optional.

One method is called by location manager when it has determined current location or detects any change in location.

Other method is called when location manager encounters an error.

Page 11: iOS Core location

Getting Location Updates

When the location manager wants to inform its delegate of the current location, it calls:

locationManager:didUpdateToLocation:fromLocation

First parameter is location Manager that called the delegate.

Second is CLLocation object that defines current location of iPhone

Third parameter is CLLocation object that defines previous location from last update (will be nil if method is called first time.)

Page 12: iOS Core location

Getting Latitude and Longitude using CLLocation

CLLocation object has some properties that might be interest to your application

The latitude and longitude are stored in property called coordinate.

CLLocationDegrees latitude=theLocation.coordinate.latitude;

CLLocationDegrees longitude=theLocation.coordinate.longitude;

CLLocation object also tell you how confident the location manager is in latitude and longitude calculations by the property horizontalAccuracy which describes the radius a circle with coordinates as its center.

Page 13: iOS Core location

Getting Latitude and Longitude using CLLocation

The CLLocation object also has a property called altitude that tell you how many metres above the sea level you are:

CLLocationDistance altiude=theLocation.altitude

Each CLLocation object maintains a property called verticalAccuracy that indicate how confident core location is in its altitude determination.

If verticalAccuracy is negative core location is telling you that it cannot determine the altitude.

Page 14: iOS Core location

Getting Latitude and Longitude using CLLocation

The CLLocation object also have a timestamp that tells you when the location manager made he location determination.

CLLocation object also have a useful instance method that will let you determine the distance between two CLLocation objects. The method is called getDistanceFrom: and it works like this:

CLLocationDistance distance=[fromLocation getDistanceFrom:toLocation];

Calculation ignores the altitude as if both locations are at sea level

Page 15: iOS Core location

Error Notification

If Core location is not able to determine your current location, it will call second delegate method named locationManager:didFailWithError:.

Most likely cause of error is that user denies access as location manager needs to be authorized by the user.

So, the first time your application goes to determine location an alert will popup on screen asking user if its OK for the current program to access your location. If user clicks the Don’t Allow button,your delegate will be notified with an error code kCLErrorDenied.

Other error code is kCLErrorLocationUnnown which indicate core location unable to determine location but will keep trying.

Page 16: iOS Core location
Page 17: iOS Core location

Trying Out Core Location

Lets build a small application to detect the iPhone’s current location and total distance travelled while program has been running.

Page 18: iOS Core location

In Xcode, create a new project using view-based application template and call the project WhereAmI..

Expand the classes and resources folders and single-click WherAmIViewContoller..h and make following changes

Page 19: iOS Core location
Page 20: iOS Core location

Open WhereAmIController.xib in IB. Drag 12 labels from library to the view window.

Labels on the right side after designing the application, should be connected to proper outlets

Go back to Xcode.

Open WhereAmIController.m

Page 21: iOS Core location
Page 22: iOS Core location
Page 23: iOS Core location

CLLocationManager Delegate Method

Page 24: iOS Core location
Page 25: iOS Core location
Page 26: iOS Core location

Finished Application

Page 27: iOS Core location

Address Book UI FrameworkExploring Contacts

Page 28: iOS Core location

Address Book UI

The Address Book UI framework provides controllers that facilitate displaying, editing, selecting, and creating records in the Address Book database.

On the iPhone, contact data resides in the home Library folder. On the Macintosh simulator, you can freely access these files in ~/Library/Application Support/iPhone Simulator/User/Library.

Page 29: iOS Core location

Address Book UI

The two files, AddressBook/AddressBook.sqlitedb and AddressBook/AddressBookImages.sqlitedb use standard SQLite3 to store contact information and optional contact images.

On the iPhone, you cannot access these directly.The files live in /var/mobile/Library/AddressBook

The Address Book UI framework provides two key user interfaces: a people "picker" navigation controller to choose contacts, and a view controller to display a single contact.

Page 30: iOS Core location

Working with Address Book Objects

There are four basic objects that you need to understand in order to interact fully with the Address Book database: address books, records, single-value properties, and multivalue properties

Page 31: iOS Core location

Address Book

Address books let you interact with the Address Book database and save changes to it. To use an address book, declare an instance of ABAddressBookRef and set it to the value returned from the function ABAddressBookCreate.

After you have created an address book reference, your application can read data from it and save changes to it. To save the changes, use the function ABAddressBookSave; to abandon them, use the function ABAddressBookRevert. To check whether there are unsaved changes, use the function ABAddressBookHasUnsavedChanges.

Page 32: iOS Core location

Person Records

Person records are made up of both single-value and multi-value properties. Properties that a person can have only one of, such as first name and last name, are stored as single-value properties. Other properties that a person can have more that one of, such as street address and phone number, are multi-value properties.

Page 33: iOS Core location

Group Records

Users may organize their contacts into groups for a variety of reasons. For example, a user may create a group containing coworkers involved in a project, or members of a sports team they play on. Your application can use groups to allow the user to perform an action for several contacts in their address book at the same time.

Group records have only one property, kABGroupNameProperty, which is the name of the group. To get all the people in a group, use the function ABGroupCopyArrayOfAllMembersWithSortOrdering or ABGroupCopyArrayOfAllMembers, which return a CFArray of ABRecordRef objects with and without sorting.

Page 34: iOS Core location

Interacting Using UI Controllers

The Address Book UI framework provides one view controller and three navigation controllers for common tasks related to working with the Address Book database and contact information.

ABPeoplePickerNavigationController prompts the user to select a person record from their address book.

ABPersonViewController displays a person record to the user and optionally allows editing.

Page 35: iOS Core location

ABNewPersonViewController prompts the user create a new person record.

ABUnknownPersonViewController prompts the user to complete a partial person record, optionally allows them to add it to the address book.

To use these controllers, you must set a delegate for them which implements the appropriate delegate protocol.

Page 36: iOS Core location

ABPeoplePickerNavigationController

Allows users to browse their list of contacts and select a person and, at your option, one of that person’s properties.

Page 37: iOS Core location

ABPersonViewController

Displays a record to the user.

Person view controller—displaying with editing allowed

Page 38: iOS Core location

ABNewPersonViewController

Allows users to create a new person

Page 39: iOS Core location

ABUnknownPersonViewController

Allows the user to add data to an existing person record or to create a new person record for the data.

Page 40: iOS Core location

Create the Project

In Xcode, create a new project from the View Based Application template. Save the project as QuickStart. The next step is to add the frameworks you will need. First, go to your project window and find the target named QuickStart in the Targets group. Open its info panel (File > Get Info) and, in the General tab, you see a list of linked libraries. Add the Address Book and Address Book UI frameworks by clicking the plus button and selecting them from the list.

Page 41: iOS Core location

QuickStartViewController.xib.

Page 42: iOS Core location

QuickStartViewController.h

@interface QuickStartViewController : UIViewController <ABPeoplePickerNavigationControllerDelegate> {

IBOutlet UILabel *firstName; IBOutlet UILabel *lastName;

} @property (nonatomic, retain) UILabel *firstName;@property (nonatomic, retain) UILabel *lastName; - (IBAction)showPicker:(id)sender;

@end

Page 43: iOS Core location

QuickStartViewController.m

#import "QuickStartViewController.h“ @implementation QuickStartViewController

@synthesize firstName;@synthesize lastName; -(IBAction)showPicker:(id)sender {

ABPeoplePickerNavigationController *picker =

[[ABPeoplePickerNavigationController alloc] init]; picker.peoplePickerDelegate = self; [self

presentModalViewController:picker animated:YES]; [picker release];

}

Page 44: iOS Core location

you will now begin implementing the delegate protocol, by adding two more methods.

If the user cancels, the first method is called to dismiss the people picker.

If the user selects a person, the second method is called to copy the first and last name of the person into the labels and dismiss the people picker.

Page 45: iOS Core location

(void)peoplePickerNavigationControllerDidCancel: (ABPeoplePickerNavigationController*)peoplePicker

{ [self dismissModalViewControllerAnimated:YES];

}

Page 46: iOS Core location

- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person

{ NSString* name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); self.firstName.text = name; [name release]; name = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty); self.lastName.text = name; [name release]; [self dismissModalViewControllerAnimated:YES]; return NO;

}

Page 47: iOS Core location

To fully implement the delegate protocol, you must also add one more following function. The people picker calls this third function when the user taps on a property of the selected person in the picker. In this application, the people picker is dismissed when the user selects a person, so there is no way for the user to select a property of that person. This means that the third method can never be called. However if it were left out, the implementation of the protocol would be incomplete.

Page 48: iOS Core location

(BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson: (ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

return NO;}

(void)dealloc {

[firstName release]; [lastName release]; [super dealloc];

} @end

Page 49: iOS Core location

Make Connections

In the Identity inspector (Tools > Identity Inspector), verify that the class identity of File’s Owner is QuickStartViewController—it should already be set correctly for you by the template. Connect the outlets for firstName and lastName from File’s Owner to the first name and last name labels. Finally, connect the Touch Up Inside outlet from the button to File’s Owner and select the showPicker method.

Page 50: iOS Core location

Launch Agents and Daemons

Page 51: iOS Core location

For Mac Applications

Items that start on power up:

The LaunchDaemons folders contain items that will run as root, generally background processes.

The LaunchAgents folders contain jobs, called agent applications, that will run as a user or in the context of userland.

If your job needs to run even when no users are logged in, put it in /Library/LaunchDaemons.- If it is only useful when users are logged in, put it in /Library/LaunchAgents,or in the personal LaunchAgents directories of specific users.

Do not put your job in /System/Library, which is reserved for system-provided daemons.

Page 52: iOS Core location

THANKS