I'm trying to use the CLLocationManager
framework in my iOS project to access the user's location but when I call
[locationManager startUpdatingLocation]
neither locationManager:didUpdateLocations:
or locationManager:didFailWithError:
are getting called.
//myViewController.h
@interface myViewController : UITableViewController <CLLocationManagerDelegate>
@end
//myViewController.m
@implementation myViewController{
CLLocationManager *locationManager;
}
//edit
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
}
//finish edit
-(void)getLocation
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)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 didUpdateLocations:(NSArray *)locations
{
CLLocation *newLocation = locations[[locations count] -1];
CLLocation *currentLocation = newLocation;
NSString *longitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
if (currentLocation != nil) {
NSLog(@"latitude: %@", latitude);
NSLog(@"longitude: @"%@", longitude);
}else {
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[errorAlert show];
}
}
@end
Neither delegate method is being called despite what it says in the documentation:
"This method returns immediately. Calling this method causes the location manager to obtain an initial location fix (which may take several seconds) and notify your delegate by calling its locationManager:didUpdateLocations:
method [...] In addition to your delegate object implementing the locationManager:didUpdateLocations:
method, it should also implement the locationManager:didFailWithError:
method to respond to potential errors."
Don't know how to debug the issue.
Thanks,
JA
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…