0

in .h file

#import <MapKit/MapKit.h>
@interface FirstViewController : UIViewController <MKMapViewDelegate,MKReverseGeocoderDelegate,CLLocationManagerDelegate>
{

}

in .m file

-(void)viewDidLoad
{
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

    [super viewDidLoad];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{
     MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
     geoCoder.delegate = self;
     [geoCoder start];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{
     NSLog(@"locationManager:%@ didFailWithError:%@", manager, error);
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
     MKPlacemark * myPlacemark = placemark;

     NSString *kABPersonAddressCityKey;
     NSString *city = [myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];

     lblAddress.text = city;

     NSLog(@"city detail is:--> %@",city);
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);
}

This is the code which I have done to get the current location of user & print it in the label.

But the CLLocationManager delegate method (which are written above) is not called & I am not able to get the current address.

Please help me out.

Where I am doing mistake...? guide me.

Thanks.

4

2 回答 2

1

In your method viewDidLoad:

-(void)viewDidLoad
{
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

    myMapView.showsUserLocation = YES;     // add this line

    [super viewDidLoad];
}

And you are done!!!

于 2012-07-13T07:05:43.190 回答
1

Instead of autoreleasing the CLLocationManager instance, assign it to an ivar in your class. Then release it in -dealloc as usual (or in one of the delegate methods if you don't need it any longer).

I suspect your location manager is getting deallocated on the next turn of the run loop before having an opportunity to fire off its delegate methods.

于 2012-07-13T07:06:19.840 回答