didUpdateLocation Method Never Called - iphone

I am making one app on iphone sdk4.0.In that did update location method never called.
I have given my code below.Please help.Thanks in advance.
-(id)init
{
[super init];
obj=[[UIApplication sharedApplication]delegate];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
//locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
return self;
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"%f",newLocation.coordinate.latitude);
NSLog(#"%f",newLocation.coordinate.longitude);
obj=[[UIApplication sharedApplication]delegate];
location=[[CLLocation alloc]initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
obj.lattitude1=[NSString stringWithFormat:#"%f",newLocation.coordinate.latitude];
obj.longitude1=[NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
//location=[[CLLocation alloc]initWithLatitude:39.9883 longitude:-75.262227];
}

Furthermore in iOS8 you must have two extra things:
Add a key to your Info.plist and request authorization from the location manager asking it to start.
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
You need to request authorization for the corresponding location method.
[self.locationManager requestWhenInUseAuthorization]
[self.locationManager requestAlwaysAuthorization]
Code example:
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Source: http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/

HI, your codes seems ok.
now these can be possible reasons :
on your init: try to check if there is locationServicesEnabled or not.
locationManager = [[CLLocationManager alloc] init];
if(locationManager.locationServicesEnabled == NO){
//Your location service is not enabled, Settings>Location Services
}
other reason, you may disallow to get location to your app.
solution: simply remove your application from iPhone and re-build, now it should popup dialog to Allow location.
use this to check error
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Error while getting core location : %#",[error localizedFailureReason]);
if ([error code] == kCLErrorDenied) {
//you had denied
}
[manager stopUpdatingLocation];
}
otherwise all seems ok,
you were already running ios 4.0 , which can be install in iPhone 3G and later,
if it was iPhone 2g, then this problem may occur.

Make sure you added CLLocationManager as a property.
#property (nonatomic , strong) CLLocationManager *locationManager;

If you are testing this on the simulator it will not work.
This happens because that method is only called when the device changes location (and the simulator never changes location).

Does -locationManager:didFailWithError: in your delegate ever get called? Maybe you denied access to location data at some point and now don't get prompted, but access is denied.

After you alloc and init your location manager, check to see if location services are allowed. This code is from Apple's "LocateMe" code sample
if (locationManager.locationServicesEnabled == NO) {
UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:#"Location Services Disabled" message:#"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[servicesDisabledAlert show];
[servicesDisabledAlert release];
}
If you're testing with the simulator, try testing with a device instead. The simulator requires that the computer's WiFi is turned on, and that it can locate a WiFi base station that's in it's database of known locations.

Related

Updating user location using iPhone GPS without internet

I need to get user location and fetch latitude and longitude of even when there is no internet available.
Right now i have implemented CoreLocation methods:-
-(void)updatestart
{
// Current location
_locationManager = [[CLLocationManager alloc]init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
[_locationManager stopUpdatingLocation];
NSLog(#"%f",_locationManager.location.coordinate.latitude);
NSLog(#"%f",_locationManager.location.coordinate.longitude);
}
and i am getting the location updates but this only works if we have internet connection.
I guess using iPhone GPS we can fetch the location even without internet.
Any idea of how to implement that??
Thanks in advance.
GPS doesn't need data exchange using internet, but it has basically 2 disadvantages:
it takes a long time to get position if you haven't used it recently (this is
due to satellite search)
it doesn't work inside buildings or where streets are too small
between buildings (this happens a lot in Italy)
Another way that it doesn't need data exchange is location based on cell tower, but of course your device should have cellular chip installed.
From your code I see three things that should be fixed as soon as possible.
Sometimes the first location is cached and it doesn't represent the
actual location
It will be better to stop the location manager when you receive a
valid coordinate, that means: not cached, with an horizontal accuracy >=0 and with an horizontal accuracy that match your requirements,
The delegate methods to get location is deprecated (depending on your
deployment target). Here is a little snippet for the first two
points:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation * newLocation = [locations lastObject];
if (newLocation.horizontalAccuracy < 0) {
return;
}
NSTimeInterval interval = [newLocation.timestamp timeIntervalSinceNow];
if (abs(interval)>20) {
return;
}
}

MKReverseGeocoder location finder error {PBHTTPStatusCode=503} response in didFailWithError: delegate iPhone?

Am using MKReverseGeocoder to find the current location in my iPhone app. Now a days the app should not find the current locations. When i trouble shoot the problem i have found the following error response from - (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error delegate. The error message is,
SourceCache/ProtocolBuffer/ProtocolBuffer-92/Runtime/PBRequester.m:687 server returned error: 503
2012-07-10 12:21:29.773 Dial25[3046:707] didFailWithError:- Error Domain=NSURLErrorDomain Code=-1011 "The operation couldn’t be completed. (NSURLErrorDomain error -1011.)" UserInfo=0x264090 {PBHTTPStatusCode=503}
I have used Google and found the answer to add [geoder autorelease]; in the didFailWithError: delegate but still my app should not find the current locations.
-(void)startFindLocationService
{
NSLog(#"Starting Location Services");
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 20.0f;
}
-(void)findAddressByLatLong:(CLLocation *)currentLocation
{
CLLocationCoordinate2D locationToLookup = currentLocation.coordinate;
MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:locationToLookup];
reverseGeocoder.delegate = self;
[reverseGeocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(#"Error: %#", [error description]);
[geocoder cancel];
geocoder.delegate = nil;
[geocoder autorelease];
}
Can anyone please help me to solve the problem? Thanks in advance.
I am attempting to learn more about geocoding myself and may have found some other references that will be helpful.
Several MKReverseGeocoder class methods have been deprecated since iOS 5:
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/doc/uid/TP40008323-AppendixA
There were problems back in 2010 with Google only responding to MKReverseGeocoder requests at certain times of day. I do not know if this is relevant to your issue, but perhaps it has something to do with why Apple deprecated the methods.
http://blog.aribraginsky.com/2009/12/curious-case-of-mkreversegeocoder.html
See Rohan Kapur's solution to MKReverseGeocoder bugs by switching to CLGeocoder:
Using MKReverseGeocoder in a singleton class (ARC)
Hope this helps!

How to get the user's current location by code in iphone app?

I want to get the user's current location from my iPhone app. I want to show the user's current location like country name, latitude, longitude information in my app. And also i want to show the location in Google map also. I have tried Google search also, but can't get the exact answer. I have get the info that was to use CLLocationManager in my app to track the location. How do i use this? I have download one sample app from Apple Documents. Here is the link: https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html
Can you please help me on this? Thanks in advance.
1) I have get the info that was to use CLLocationManager in my app to track the location. How do i use this?
in .h file
#include <CoreLocation/CLLocationManagerDelegate.h>
#include <CoreLocation/CLError.h>
#include <CoreLocation/CLLocation.h>
#include <CoreLocation/CLLocationManager.h>
CLLocationManager * myLocationManager;
CLLocation * myLocation;
in .m file :-
-(void)findMyCurrentLocation
{
self.myLocationManager = [[[CLLocationManager alloc] init] autorelease];
[[self myLocationManager] setDelegate:self ];
[myLocationManager startUpdatingLocation];
double latitude=34.052234;
double longitude=-118.243685;
CLLocation *defaultLocation =[[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[self setMyLocation:defaultLocation];
[defaultLocation release];
if( [CLLocationManager locationServicesEnabled] )
{
NSLog(#"Location Services Enabled....");
locationServicesEnabled=TRUE;
UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:#"Information"
message:#"Fetching your current location."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil ];
[alert release];
}
else
{
NSLog( #"Location Services Are Not Enabled...." );
locationServicesEnabled=FALSE;
UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:#"Information"
message:#"Location service is not enable. Please enable it from settings."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil ];
[alert release];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[self setMyLocation:newLocation];
NSString *tempLat = [ NSString stringWithFormat:#"%3.6f" , (newLocation.coordinate.latitude) ];
NSString *tempLong= [ NSString stringWithFormat:#"%3.6f" , (newLocation.coordinate.longitude)];
appDelegate.curlat = tempLat;
appDelegate.curlong = tempLong;
}
- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
{
printf("\nerror");
UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:#"Error"
message:#"Error while getting your current location."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil ];
[alert release];
}
2). I want to show the user's current location like country name information in my app.
For this you can to use Google's Reverse Geo coding OR MKReverseGeocoder
this should do most of it..
http://www.highoncoding.com/Articles/804_Introduction_to_MapKit_Framework_for_iPhone_Development.aspx
to get the information on the location you need to use MKReverseGeocoder
https://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323
First create an instance of the MKMapView
To get user's latitude and longitude:
In your viewDidLoad
[yourMapView setShowsUserLocation:YES];
CLLocationCoordinate2D userCoord;
userCoord.latitude=map_view.userLocation.coordinate.latitude;
userCoord.longitude=map_view.userLocation.coordinate.longitude;
//NSLogging these on simulator will give you Cupertino or whatever location you set in location simulation.
And for country name you will need reversegeocoding you can look at the class reference here
https://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323
OR
If MKReverseGeoCoding gets too complicated you can use Yahoo's reversegeocoder
http://where.yahooapis.com/geocode?q=%f,%f&gflags=R&appid=yourAppId, those 2 %f will be userCoord.longitude and userCoord.latitude.
Yes you can use CLGeoCoder. But CLGeaCoder will not provide accrurate location inforamtion outside of USA for other country like India etc. So better to use Google's Reverse Geo coding SVGeoCoder. SVGeoCoder have nice implementation to get location with goolePlaceAPI.

iphone gps giving incorrect location

I want to show user's current location with iphone gps feature but problem is it is giving incorrect location .
When i drop pin on map then it drops pin at exact position but when i try to see the location in text then it gives inaccurate location with inaccuracy of 500 to 800 meters approx.I have used reverse geocoding and google api but all giving same location. PLease tell me why this happens and how can i show the exact location of user ?
My code is:
cllocationmanager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
[locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLLocationCoordinate2D here = newLocation.coordinate;
NSLog(#"%f %f ", here.latitude, here.longitude);
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:here];
[geocoder setDelegate:self];
[geocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
NSLog(#"The geocoder has returned: %#", [placemark addressDictionary]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"%#",[placemark addressDictionary]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
Quick guess: did you check the CLLocation's horizontal accuracy? Quite often the first response I get is very inaccurate, and then subsequent calls get better.
Edit: #pankaj First of all, can you confirm that it is an accuracy issue. If it is the problem that I'm suggesting, then the CLLocation horizontalAccuracy will be large. If not the case then you can ignore my answer and these comments. However, if horizontalAccuracy is a large error then you will have to wait for a better lock. There are two ways to do this:
Wait for a short period of time (a second or two) and see if you get a better lock.
Start requesting location much earlier on, e.g. when the app launches, or when the UIViewController that requires location starts.

CLLocation manager keep getting same latitude and longitude when clicking button?

This is my first question in this site.
I have this serious problem.... I'll explain this from the beginning…
in my app i need to get the current location of the user when the user click on the button in the application.. but the problem is when is click on the button its not updating to the current location its getting the previous location. But when i reset the location warnings in the iphone app its get the correct location.
Here is the code steps i did for this application to get the current location of the user...
First I import to the application ...
then i am using global files to keep data of the application because i need to access them through the application.
so what I did in the globle.m and .h file is ...
CLLocationManager* locationManager;
#synthesize locationManager
+ (Globals*)sharedGlobals {
#synchronized(self) {
if(_sharedGlobals == nil) {
_sharedGlobals = [[super allocWithZone:NULL] init];
_sharedGlobals.locationManager = [[CLLocationManager alloc]init];
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
}
return _sharedGlobals;
}
Then in my other view controller I put the CLLocationManagerDelegate and in the .m file
-(IBAction) didTapSearchbtn{
if (![CLLocationManager locationServicesEnabled]) {
}else {
[[Globals sharedGlobals].geoLocations removeAllObjects];
search.text = nil;
[Globals sharedGlobals].fromTextField = NO;
[[Globals sharedGlobals].locationManager setDelegate:self];
[[Globals sharedGlobals].locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (newLocation.horizontalAccuracy < 0) return;
[[Globals sharedGlobals].locationManager setDelegate:nil];
[[Globals sharedGlobals].locationManager stopUpdatingLocation];
[[Globals sharedGlobals].geoLocations setObject:[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude] forKey:#"geolat"];
[[Globals sharedGlobals].geoLocations setObject:[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude] forKey:#"geolong"];
[self retriveDataFromInternet];
[[Globals sharedGlobals].locationManager release];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//GPS error
[[Globals sharedGlobals].locationManager setDelegate:nil];
[[Globals sharedGlobals].locationManager stopUpdatingLocation];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"YumTable!", nil) message:NSLocalizedString(#"Enable Your GPS settings to get your current location", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"Ok", nil) otherButtonTitles:nil];
[alert show];
[alert release];
[[Globals sharedGlobals].locationManager release];
}
i put the label to my view controller and went different places to take latitudes and longitudes .. but always it getting same latitude and longitude ... but when I reset the location warnings and run the app again it took the correct latitude and longitude ... so if i need to take current location always i have to reset it. But what i need is to get current location every time when i click the search button...
Can any one can say whats wrong in this code and can any one help me ....
And Also very very sorry about my bad english ... :)
The LocationManager will return the previos location because it tries to be as fast as possible and it thinks that this location might be good enough. I usually check the timestamp on the new location to ensure that it is a fresh one. If it is to old I don't stop the manager and wait for the next one.
I would suggest that you look at the sample code provided by Apple, https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007801
This code is copied from the example:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
}
I missed Typed my code ... after I figur that out my application start to work perfectly ... Thank you guys for your great help..
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
instead of that I used
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBestforNavigation];