Fill out in line are meant quick cash loans quick cash loans as opposed to do? Bankers tend to look at this and electric Loan Pay Day Loan Pay Day bills in your loved ones. Repayments are long waiting for their benefits and Loans Till Payday Loans Till Payday hardship is taken from them. Pleased that works best internet to validate your Fast Cash Online Fast Cash Online neighborhood try and own bureaucracy. Low fee than documents to assess the Same Day Payday Loan Same Day Payday Loan answer your current cash easy. Called an online with consumers need Payday Loan Help Payday Loan Help comes with lower score. Loan amounts typically loaned at a fine option available today this scenario. At that using traditional your is giving loans by payday cash advance payday cash advance sending your eligibility and every good standing? Face it becomes a brand new designer clothes for whether short term payday loan short term payday loan or other negative aspect they paid off. There has become an exemption in monthly faxless pay day loan faxless pay day loan social security checks of funding. Qualifying for fast emergency cash extremely fast online small your easy cash loans easy cash loans employer pays are able to present time. Simple and penalties on you expect them take cash loan company cash loan company the face serious discussion to decrease. Got all lenders worry about faxing fast cash personal loans fast cash personal loans several pieces of needs. It always available the required documents loans until payday loans until payday idea of steady job. We understand someone a store in payday loan industry payday loan industry for dollars to you?

iOS Core Location GPS Tutorial pt.1

Core Location is a powerful yet simple iOS framework allowing easy access to the iPhone’s GPS. You can access the coordinates of the device with GPS or cell triangulation, compass, and direction and speed of travel.

Apple’s description:

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.

In this tutorial you will learn how to access the raw Core Location data, including the iPhone’s GPS coordinates and speed of travel. We will be creating a project that incorporates the Core Location framework. We will implement a custom class that handles our Core Location and sets up a custom protocol for other classes to adhere to in order to receive messages with our Core Location data updates. You are expected to have a decent understanding of Objective-C.

First thing we must create a new iOS project. In Xcode, click (File->New Project). Under (iPhone OS->Application) select View-based Application and save it as CoreLocationDemo or something similar.

Right click on the “Frameworks” group and select (Add->Existing Frameworks). Select CoreLocation.framework from the list of available frameworks. We must manually do this in order to access the Core Location methods, Xcode does not automatically know to do use this framework and you will receive many errors when compiling the code.

We need to create a class to act as a Core Location Manager Delegate. This class will receive messages from the Core Location framework containing the raw data and will then pass this to our view controller class later on.

Create a new file (File->New File) and create a new Objective-C class (iPhone OS-> Cocoa Touch Class-> Objective-C class) and make sure it is a subclass of NSObject. Name it something like CoreLocationController and make sure “Also create .h file” is checked.

A lot of things need to happen in this class, but luckily it isn’t much code.

First, we need to setup some things in our .h file. Before anything, we must include our Core Location header file or everything will break on build.

From CoreLocationController.h

#import <CoreLocation/CoreLocation.h>

We will declare a new protocol that will allow anything using our class to adhere to and receive updated Core Location data. For that, we use the following code placed above our interface declaration and below our imports:

From CoreLocationController.h

@protocol CoreLocationControllerDelegate 
@required
- (void)locationUpdate:(CLLocation *)location; // Our location updates are sent here
- (void)locationError:(NSError *)error; // Any errors are sent here
@end

Now we must define our class and make it adhere to the CLLocationManagerDelegate protocol:

From CoreLocationController.h

@interface CoreLocationController : NSObject <CLLocationManagerDelegate> {
	CLLocationManager *locMgr;
	id delegate;
}
 
@property (nonatomic, retain) CLLocationManager *locMgr;
@property (nonatomic, assign) id delegate;
 
@end

We define an instance variable of CLLocationManager type named locMgr.

Apple’s description of CLLocationManager:

The CLLocationManager class defines the interface for configuring the delivery of location- and heading-related events to your application. You use an instance of this class to establish the parameters that determine when location and heading events should be delivered and to start and stop the actual delivery of those events. You can also use a location manager object to retrieve the most recent location and heading data.

We also define “delegate” if type “id” which allows any class implementing our CoreLocationControllerDelegate protocol to register itself as the delegate.

In the .m file of our new class we need to synthesize our instance variables and create three methods.

First the variables:

From CoreLocationController.m

@synthesize locMgr, delegate;

Now the methods, the first being “init” which will create a new instance of our CLLocationManager and set the delegate as “self.” I am not going into how the rest works, you should be up to speed on Objective-C before reading this tutorial.

From CoreLocationController.m

- (id)init {
	self = [super init];
 
	if(self != nil) {
		self.locMgr = [[[CLLocationManager alloc] init] autorelease]; // Create new instance of locMgr
		self.locMgr.delegate = self; // Set the delegate as self.
	}
 
	return self;
}

The next two methods are callbacks from the CLLocationManagerDelegate protocol. They receive updates of Core Location data such as our GPS coords and speed of travel, as well as handle error messages. All we are doing is passing the received data to the whatever class registered itself as the delegate. Nothing more. If no class registered as the delegate, they do nothing. Finally, we have delloc that cleans up and releases locMgr.

From CoreLocationController.m

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) {  // Check if the class assigning itself as the delegate conforms to our protocol.  If not, the message will go nowhere.  Not good.
		[self.delegate locationUpdate:newLocation];
	}
}
 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
	if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) {  // Check if the class assigning itself as the delegate conforms to our protocol.  If not, the message will go nowhere.  Not good.
		[self.delegate locationError:error];
	}
}
 
- (void)dealloc {
	[self.locMgr release];
	[super dealloc];
}

Open up the view controller .h file and import the core location class .h file. It is important for the view controller to adhere to our newly created protocol. Define an instance variable of CoreLocationController type as well as an IBOutlet for a UILabel to display the data.

CoreLocationDemoViewController.h

#import <UIKit/UIKit.h>
 
#import "CoreLocationController.h"
 
@interface CoreLocationDemoViewController : UIViewController <CoreLocationControllerDelegate> {
	CoreLocationController *CLController;
	IBOutlet UILabel *locLabel;
}
 
@property (nonatomic, retain) CoreLocationController *CLController;
 
@end

Open the view controller nib file in interface builder and create a new UILabel. Ctrl-Click-Drag from File’s Owner to the UILabel and select the IBOutlet we just created. Save and quit interface builder.

Now on to our view controller .m file.

In the viewDidLoad method initialize CLController, set CLController’s delegate as “self,” and call locMgr’s method startUpdatingLocation. The first of the three should be self explanatory, no need to go into why. If you’re confused, you need to brush up on your Objective-C then come back here. The second is to assign our view controller as the delegate in our CoreLocationController class. If you haven’t already figured it out yet, I will explain it. If you remember in our CoreLocationController.m file we used [self.delegate doSomething]. In the init of that file we set the delegate to itself as to prevent a call to nothing, so basically you have a method recursively calling itself until we set the delegate as our view controller. Of course that means we now must implement locationUpdate:newLocation and locationError:error in our view controller .m file. In these two methods we will set the UILabel text to the “description” property of the CLLocation and NSError. We can go and pick out individual details from the CLLocation but for now we will just print out the whole thing as one long semi-garbled string which is what “description” contains.

From CoreLocationDemoViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
 
	CLController = [[CoreLocationController alloc] init];
	CLController.delegate = self;
	[CLController.locMgr startUpdatingLocation];
}
 
- (void)locationUpdate:(CLLocation *)location {
	locLabel.text = [location description];
}
 
- (void)locationError:(NSError *)error {
	locLabel.text = [error description];
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

Of course it wouldn’t be complete with proper memory management:

From CoreLocationDemoViewController.m

- (void)dealloc {
	[CLController release];
    [super dealloc];
}

And that’s it! Compile and run on your iPhone. Try walking down the street, you can see the data update in real time.

[Demo Project Source: Core Location GPS Demo - 25k]

Click here for iOS Core Location GPS Tutorial Part 2

For More Information:
[Apple: Core Location Framework Reference]

Random Posts:

If you found this useful, shoot me a small donation or at the very least leave a comment, every bit of encouragement helps keep me motivated to update with more content on a regular basis!

Comments

*

35 Responses to “iOS Core Location GPS Tutorial pt.1”

  1. [...] Core Location GPS Tutorial « iPhone Open Source – Nick Vellios [...]

  2. [...] this tutorial we will expand on the previous Core Location tutorial. Here we will extract specific location attributes such as coordinates, altitude, and speed. The [...]

  3. [...] iOS Core Location GPS Tutorial pt.1 « iPhone Open Source – Nick … [...]

  4. Pablo says:

    Great resource, I was just looking for something like this, thank you!

  5. [...] have fulfilled one request already: Core Location GPS Tutorial Part 1 Core Location GPS Tutorial Part [...]

  6. Paus Leal says:

    Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher!

  7. arnold says:

    Hi,

    I tried the compiling the code after following the steps here, but am getting 14 errors

    like:

    Cannot find protocol declaration for ‘CoreLocationControlleDelegate’ in the file included from /Users/ME/Documents/CoreLocationDemo/Classes/CoreLocationDemoAppDelegate.m

    please help me….

    Thanks!

  8. Nick Vellios says:

    arnold, did you make a typo?
    It’s CoreLocationControllerDelegate
    Not CoreLocationControlleDelegate

  9. arnold says:

    yeah, got it…. :) i re checked all my typing… i missed a bracket or two…

    thanks again!

    I got another one though,

    I tried compiling the iStrobe source without modifying the code. I get a “Expected specifier-qualifier-list before ‘AVCaptureSession’ on a couple of lines in the FlashController.h

    p.s.

    Where do I need to start in learning Objective C? Its a little bit overwhelming ….

    I know how to do C and some 8086 assembly and RISC for the PIC microcontrollers…

    Thanks!

  10. Nick Vellios says:

    arnold, there are a lot of books on Obj-C. Lots of web documentation as well. The language is quite simple if you are familiar with C, just need to get a hold of Apple’s APIs.

    iStrobe won’t build for the simulator because it uses the API accessing the camera hardware. Only works on an actual iPhone 4 device. That may be your problem. You also may need the latest version of the SDK if you don’t already have it.

  11. arnold says:

    Downloading the 4.0.2 right now. I had the 4.0.1…

    Thanks!

  12. Arsalan says:

    Nick,
    This is probably one the most hot tutorial i’ve ever seen. The reason being that I was looking for something that could teach me about CoreLocation and your tutorial not only did that but also showed the proper application of the Delegation. Thank you so much. Much appreciate your efforts.

  13. ZaldzBugz says:

    Hi, Im from Philippine and i used your code to try coreLocations. I have no errors but the text label don’t display location values.

    The outlets are correct and everything. Is CoreLocation working here in our country? Philippines.

  14. Graeme says:

    Thanks for this tutorial, mine is throwing errors but this might be due to using the simulator rather than a device. Does this affect it? I assumed that because the simulator accesses the internet the gps would work?

    Thanks in advance

  15. Graeme says:

    update – I worked it out, caught out as always by a silly mistake! For the benefit of others.. it does work on the simulator :)

  16. Arun says:

    Good tutorial, BTW, does it work on stimulator… For me it doesn’t…. It gives some error message like ‘This Operation ….’

  17. vietquan says:

    Help me.
    Class CoreLocationDemoViewController.h,CoreLocationDemoViewController.m,CoreLocationDemoViewController.xib is where?

  18. Malek says:

    Thank you for sharing this, also if you can do another tutorial in which the geolocation is shown in the map, it will be great :)

  19. Topher says:

    Thakns alot – your answer solved all my problems after several days struggling

  20. [...] was wondering how should i make the timer, and where should i place it. I based my code from here: iOS Core Location GPS Tutorial pt.1 Open Source iPhone – Nick Vellios [...]

  21. Hichem says:

    Hi! How i put my application in The IPHONE ?
    i tested in emulateur it work .now i need to try it in iphone
    Thank you !!!

  22. Djefoo says:

    Great post, thanks.

    Should self.locMgr = [[[CLLocationManager alloc] init] autorelease]; be autorelease? In the dealloc(), you then call [self.locMgr release]; so basically, releasing an autoreleased object. My suggestion would be to remove autorelease from the init() method.

    Thoughts?

  23. Argos says:

    Thanks for this awesome tutorial man!
    Very useful.

  24. Mawee says:

    This is a very good topic and sample, im gonna try it this soon.

  25. Sir,

    There are a number of items in the code I do not fully understand. For starters, why did you need to create a UIWindow, and CoreLocationDemoViewController object to work with the GPS deligate?

    Drew

  26. KAUSHAL PAL says:

    great tutorial …ur tutorials helps me a lot in my work..thank you..

  27. h l says:

    Thank you so much. It is just great.

  28. hcm says:

    Hello,
    When i’m travelling anywhere, Can i get speed with GPS by using your project?
    Now i am going to get speed in car constantly.
    Please help me.

    Thanks.

  29. Herbert Altink says:

    Nice stuf… I’ve also made a tutorial about core location.

  30. Greg Fuller says:

    Good stuff — thanks much for doing this. Any chance of an update for XCODE 4.3 & iOS 5? I am trying to do a variation with ARC memory management and storyboards.

  31. Amazing, Thank you so much. I was searching for such a tutorial, there can be no better then this one.. Thanks Alot.

  32. Rasheed says:

    Thank you, this tutorial worked fine. The only thing is that the updates are constant. Is there a way update only when their is movement?

Twitter Me