Aqui estão as etapas para obter informações de localização atual no iOS dev.
Primeiro, você precisa adicionar uma CoreLocation
biblioteca ao seu projeto.
Em seguida, importe <CoreLocation/CoreLocation.h>
e useCLLocationManagerDelegate
Defina 3 variáveis abaixo:
CLLocationManager *locationManager;
CLGeocoder *geocoder;
int locationFetchCounter;
instanciar essas variáveis em viewDidLoad
:
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
geocoder = [[CLGeocoder alloc] init];
}
// execute this method to start fetching location
- (IBAction)doFetchCurrentLocation:(id)sender {
locationFetchCounter = 0;
// fetching current location start from here
[locationManager startUpdatingLocation];
}
implementos locationManager:didUpdateLocations
e locationManager:didFailWithError
para manuseio [locationManager startUpdatingLocation]
do resultado.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// this delegate method is constantly invoked every some miliseconds.
// we only need to receive the first response, so we skip the others.
if (locationFetchCounter > 0) return;
locationFetchCounter++;
// after we have current coordinates, we use this method to fetch the information data of fetched coordinate
[geocoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks lastObject];
NSString *street = placemark.thoroughfare;
NSString *city = placemark.locality;
NSString *posCode = placemark.postalCode;
NSString *country = placemark.country;
NSLog("we live in %@", country);
// stopping locationManager from fetching again
[locationManager stopUpdatingLocation];
}];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"failed to fetch current location : %@", error);
}
se você executar seu aplicativo por meio do simulador de iphone no XCODE, será necessário definir a localização desejada (o simulador não consegue detectar a localização atual).