Integrating GPS to my application - iphone

I am following a tutorial to integrate GPS to my application. I want to display the Latitude and Longitude values in the viewDidLoad method. According to the tutorial they have displayed it from another method. But i need it to be displayed in viewDidLoad. How can i modify the following code to display it in viewDidLoad ?
The HelloThereController.h view controller
#import "MyCLController.h"
#interface HelloThereViewController : UIViewController <MyCLControllerDelegate> {
MyCLController *locationController;
}
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#end
The HelloThereController.m view controller
#import "HelloThereViewController.h"
#implementation HelloThereViewController
- (void)viewDidLoad {
locationController = [[MyCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
//I need to print the latitude and logitude values here..
}
My MyCLController.h class
#protocol MyCLControllerDelegate
#required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#end
#interface MyCLController : NSObject {
CLLocationManager *locationManager;
id delegate;
}
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, assign) id delegate;
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error;
#end
My MyCLController.m class
#import "MyCLController.h"
#implementation MyCLController
#synthesize locationManager;
#synthesize delegate;
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[self.delegate locationUpdate:newLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
[self.delegate locationError:error];
}
- (void)dealloc {
[self.locationManager release];
[super dealloc];
}
#end

If this view controller loads as soon as the app loads, you can't.
it takes time for the location manager to get gps updates.
you'll need to display some ui component that lets the user know you're getting the location, such as UIActivityIndicatorView, and setup another method for displaying the coordinates when you get them.

In general you can accelerate the process sacrificing some accuracy setting the desiredAccuracy property. According to the documentation the values are:
kCLLocationAccuracyBestForNavigation
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyKilometer
kCLLocationAccuracyThreeKilometers
Anyway you are interested in the first location, so still according to the documentation:
When requesting high-accuracy location data, the initial event delivered by the location
service may not have the accuracy you requested. The location service delivers the initial
event as quickly as possible. It then continues to determine the location with the accuracy
you requested and delivers additional events, as necessary, when that data is available.
You can try starting the location manager in the AppDelegate didFinishLaunchingWithOptions to have some more time before the view appears. As said by Frederick Cheung, locationManager.location can be nil, so it's better do the operations in the location manager delegate.

Related

CLLocationManager in background thread

I am doing one application.In that i am using the CLLocationManager Class for getting the updated location latitude and longitude details.But i need to use this CLLocationManager in sepaate thread .I written my code like below.
- (void)viewDidLoad
{
[NSThread detachNewThreadSelector:#selector(fetch) toTarget:self withObject:nil];
}
-(void)fetch
{
manager=[[CLLocationManager alloc]init];
manager.delegate=self;
manager.distanceFilter=kCLDistanceFilterNone;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"%f",newLocation.coordinate.latitude);
lbl.text=[NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
}
.But this delegate method is not fired when i run this code.So please guide me how to get the location updates in separate thread.
The methods of your delegate object are called from the thread in which you started the corresponding location services. That thread must itself have an active run loop, like the one found in your application’s main thread. ——from apple document
Could you please tried with this.
dispatch_async(newThread, ^(void) {
[self fetch];
});
hope you'll get solved problem.
in .h file
MainView *ctl;
NSMutableDictionary *dictSubPoses;
- (id)initWithCtl:(MainView*)_ctl;
in .m file
- (id)initWithCtl:(MainView*)_ctl
{
if(self = [super init])
{
ctl = _ctl; //[_ctl retain];
}
return self;
}
- (void)main
{
[ctl performSelector:#selector(yourMethod) withObject:dictSubPoses];
}
in .h file
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
//Set Delegate
CLLocationManagerDelegate
// Declare
CLLocationManager *locationManager;
in .m file
-(void)ViewDidLoad
{
locationupadate=YES;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 100.0f;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if(locationupadate)
{
NSLog(#"%f",newLocation.coordinate.latitude);
lbl.text=[NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
}

How do I get exact coordinates using iPhone CLLocationManager

I am using CLLocationManager *locationManager and getting coordinates but these coordinates are not exact as google map coordinates.
iPhone coordinates are the following
<+26.86126232,+75.75962328>+/-100.00m(speed -1.00 mps/course-1.00)
google map coordinates for same device's location place coordinates are following
<+26.860524,+75.761569>
Google map coordinates are right but iPhone coordinates are wrong these are 100 meter away from google map's exact coordinates.
How do I get the exact coordinates.
// MyCLController.h
// mapCurrentLocation
//
// Created by mac on 18/11/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#protocol MyCLControllerDelegate
#required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#end
#interface MyCLController : NSObject<CLLocationManagerDelegate> {
IBOutlet UILabel *locationLabel;
CLLocationManager *locationManager;
id delegate;
}
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, assign) id delegate;
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error;
#end
//
// MyCLController.m
// mapCurrentLocation
//
// Created by mac on 18/11/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "MyCLController.h"
#implementation MyCLController
#synthesize locationManager;
#synthesize delegate;
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self; // send loc updates to myself
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// NSLog(#"Location: %#", [newLocation description]);
[self.delegate locationUpdate:newLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
//NSLog(#"Error: %#", [error description]);
[self.delegate locationError:error];
}
- (void)dealloc {
[self.locationManager release];
[super dealloc];
}
#end
and here i am using this class--
#import "mapCurrentLocationViewController.h"
#implementation mapCurrentLocationViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
- (void)viewDidLoad {
locationController = [[MyCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
}
- (void)locationUpdate:(CLLocation *)location {
locationLabel.text = [location description];
}
- (void)locationError:(NSError *)error {
locationLabel.text = [error description];
}
- (void)dealloc {
[locationController release];
[super dealloc];
}
#end
To get the most accurate possible location measurements, set locationManager.desiredAccuracy = kCLLocationAccuracyBest; before you startUpdatingLocation.
Also, check the timestamp and horizontalAccuracy of the CLLocation objects that get delivered to locationManager:didUpdateToLocation:fromLocation:. If the location measurement seems like it's older or less accurate than you'd like, set a timer and wait for some more location measurements to be delivered. Core Location will often deliver a cached and/or imprecise location quickly, and then follow up with refined location measurements that are more accurate.

CLLocationManager startUpdatingLocation using a UIButton

This is the first time I am using CLLocationManager. I am not sure if i am doing the right thing. Correct me if i am wrong.
I initialize the locationManager in my viewDidLoad Method and tell the locationManager to startUpdatingLocation in the same method.
When the delegate receives
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
[locationManager stopUpdatingLocation];
//do stuff with the coordinates
}
to avoid repeated calls to this delegate method.
I have a UIButton where users can click to update the location
//called by user action
-(IBAction)updateLocation{
//start updating delegate
locationManager.delegate=self;
[locationManager startUpdatingLocation];
}
However when the location changes and when I click the UIbutton, the location coordinates donot change at all. :(
What am i doing wrong? Is this the right of doing or should i not stop the locationManager at all ?
Help would be appreciated.
CLLocationManager caches your last location and returns it as soon as you call -startUpdatingLocation. So, you are starting updates, receiving the old location, and then stopping updates.
This isn't how -startUpdatingLocation/-stopUpdatingLocation are meant to be used. As I asked above, what's wrong with calling the delegate method multiple times? If you only want to get the location when the user taps a button, leave the CLLocationManager updating, and just check CLLocationManger's location property when the user taps your button.
If the reason you're trying to avoid multiple calls to the delegate method is because you're worried about power consumption, etc., adjust the desiredAccuracy property of the CLLocationManager with something like: locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters.
All told, it might look something like this...
.h file:
#interface YourController : NSObject <CLLocationManagerDelegate>
#property (nonatomic, retain) CLLocationManager *locationMgr;
#property (nonatomic, retain) CLLocation *lastLocation;
- (IBAction)getNewLocation:(id)sender;
#end
.m file:
#interface YourController
#synthesize locationMgr = _locationMgr;
#synthesize lastLocation = _lastLocation;
- (id)init
{
if (self = [super init]) {
self.locationMgr = [[CLLocationManager alloc] init];
self.locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
self.locationMgr.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (!self.lastLocation) {
self.lastLocation = newLocation;
}
if (newLocation.coordinate.latitude != self.lastLocation.coordinate.latitude &&
newLocation.coordinate.longitude != self.lastLocation.coordinate.longitude) {
self.lastLocation = newLocation;
NSLog(#"New location: %f, %f",
self.lastLocation.coordinate.latitude,
self.lastLocation.coordinate.longitude);
[self.locationMgr stopUpdatingLocation];
}
}
- (IBAction)getNewLocation:(id)sender
{
[self.locationMgr startUpdatingLocation];
NSLog(#"Old location: %f, %f",
self.lastLocation.coordinate.latitude,
self.lastLocation.coordinate.longitude);
}
- (void)dealloc
{
[self.locationMgr release];
self.locationMgr = nil;
[self.lastLocation release];
self.lastLocation = nil;
[super dealloc];
}
#end
Am assuming you have included #import <CoreLocation/CoreLocation.h> framework to being with. This is the way you start getting location updates.
CLLocationManager *locationMgr = [[CLLocationManager alloc] init];
locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
locationMgr.delegate = self;
[locationMgr startUpdatingLocation];
You are correct here. After this you start getting location updates, here in this delegate-
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// Handle location updates
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// Handle error
}

CLLocationManager - strange Memory Leak

I'm implementing a CLLocationManager right as described in several tutorials.
Everything works fine up to the point where the LocationManager receives a second update. Then a memory leak occurs.
Instruments tells me, that the leaked objects are NSCFTimer, GeneralBlock-16 and NSCFSet
Any ideas?
Thanks for any help
[Edit]
After repeatingly starting and stopping the locationManager, the updated seem to come faster. This makes me think that the CLLocationManager initializes a new timer every time a location-update occurs... VERY strange...
And - so you don't need to read my comment - the app crashes after a while
[Edit]
Ok - I don't get it here's some code...
I'm using a separate class for the locationManager, as described here: http://www.vellios.com/2010/08/16/core-location-gps-tutorial/
locationManager.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#protocol locationManagerDelegate
#required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#end
#interface locationManager : NSObject <CLLocationManagerDelegate>{
CLLocationManager *myLocationManager;
id delegate;
CLLocation *bestEffortAtLocation;
BOOL outOfRange;
}
#property (nonatomic, retain) CLLocationManager *myLocationManager;
#property (nonatomic, retain) CLLocation *bestEffortAtLocation;
#property (nonatomic, assign) id delegate;
#property (nonatomic, assign) BOOL outOfRange;
#end
locationManager.m
#import "locationManager.h"
#implementation locationManager
#synthesize myLocationManager;
#synthesize delegate;
#synthesize bestEffortAtLocation;
#synthesize outOfRange;
- (id) init {
self = [super init];
NSLog(#"initializing CLLocationManager");
if (self != nil) {
outOfRange = NO;
self.myLocationManager = [[[CLLocationManager alloc] init] autorelease];
self.myLocationManager.delegate = self;
self.myLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[self performSelector:#selector(stopUpdatingLocation:) withObject:#"Timed Out" afterDelay:100.0];
}else{
NSLog(#"Location Manager could not be initialized");
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if(outOfRange == NO){
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(stopUpdatingLocation:) object:nil];
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
[self.delegate locationUpdate:newLocation];
}else{
[self.myLocationManager stopUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"error!!!!");
[self.myLocationManager stopUpdatingLocation];
[self.delegate locationError:error];
}
- (void)dealloc {
[myLocationManager release];
[bestEffortAtLocation release];
[super dealloc];
}
#end
then, in the main-class I call:
mainFile.h (exerpt)
#import "locationManager.h"
#interface mainFile : UIViewController <locationManagerDelegate , UIAlertViewDelegate>{
locationManager *locationController;
CLLocation *myLocation;
}
#end
mainFile.m (exerpt)
#import "locationManager.h"
#implementation mainFile
#synthesize locationController;
#synthesize myLocation;
- (void)locationError:(NSError *)error{
// Do alert-Stuff
}
- (void)locationUpdate:(CLLocation *)location {
// Do location-Stuff
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationController = [[[locationManager alloc] init] autorelease];
locationController.delegate = self;
[locationController.myLocationManager startUpdatingLocation];
}
- (void)dealloc {
self.locationController = nil;
[locationController release];
}
#end
It's driving me kinda crazy :)
My advice is to not be obsessed with one-time memory leaks that the iOS itself generates. It does this in many places and the leaks are all pretty harmless.
Ah, a long dead problem, I love them.
locationController is an iVar, not a property, so when you create it in viewDidLoad, assigning it to _locationController doesn't take on ownership.
You've autoreleased the object, so next time around the event loop, the auto-release pool is drained and it is released.
You could fix it by making it a retain property ( which would fit with your locationManager = nil ), or getting rid of the auto-release, and using an explicit [locationManager release] in dealloc.
Try doing a Build and Analyze. I usually find memory leaks and other non-syntax errors that way.

iPhone Help: Odd Memory Leak In CoreLocation Framework

I've been working to iron out memory leaks in my program and I'm down to a few stragglers. The strange thing is that they're coming from when I use CoreLocation to get a gps location. The code is properly returning the location, but it's leaking all over the place: CFHTTPMessage, CFURLConnection, CFURLRequest, CFURLResponse, GeneralBlock-16,-32,-48, HTTPRequest, etc... Could anyone please guide me how to fix this?
Initialization of MyCLController
locationController = [[MyCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
Do some things and get a call back through the delegate:
[locationController release];
MyCLController.h:
#import <Foundation/Foundation.h>
#protocol MyCLControllerDelegate
#required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#end
#interface MyCLController : NSObject {
CLLocationManager *locationManager;
id delegate;
}
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, assign) id delegate;
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error;
#end
MyCLController.m:
#import "MyCLController.h"
#implementation MyCLController
#synthesize locationManager;
#synthesize delegate;
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self; // send loc updates to myself
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
[locationManager stopUpdatingLocation];
[self.delegate locationUpdate:newLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
[self.delegate locationError:error];
}
- (void)dealloc {
[super dealloc];
}
#end
You need to release the LocationManager. Make sure that you set its delegate to NULL prior to releasing. And also, it's not a good idea to just return the first result. Make sure horizontal accuracy is not < 0 and is also below some threshold, like 5000 meters. And to make it more robust, you might want to add a timer to make it stop after a given amount of time, if it couldn't find your location accurately enough.
you never release locationController