Como posso obter a localização atual do usuário no iOS?

Como posso obter a localização atual do usuário no iOS?

   

A resposta da RedBlueThing funcionou muito bem para mim. Aqui está um exemplo de código de como eu fiz isso.

Cabeçalho

#import  #import  @interface yourController : UIViewController  { CLLocationManager *locationManager; } @end 

MainFile

No método init

 locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; 

Função de retorno

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude); NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude); } 

iOS 6

No iOS 6, a function delegada foi suspensa. O novo delegado é

 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 

Portanto, para obter a nova posição use

 [locations lastObject] 

iOS 8

No iOS 8, a permissão deve ser explicitamente solicitada antes de começar a atualizar o local

 locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) [self.locationManager requestWhenInUseAuthorization]; [locationManager startUpdatingLocation]; 

Você também precisa adicionar uma string para as chaves NSLocationWhenInUseUsageDescription ou NSLocationWhenInUseUsageDescription ao NSLocationWhenInUseUsageDescription do aplicativo. Caso contrário, as chamadas para startUpdatingLocation serão ignoradas e o seu delegado não receberá nenhum retorno de chamada.

E no final, quando você terminar de ler a localização, pare a localização da atualização no local adequado.

 [locationManager stopUpdatingLocation]; 

No iOS 6, o

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 

está obsoleto.

Use o seguinte código

 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { CLLocation *location = [locations lastObject]; NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude); } 

Para iOS 6 ~ 8, o método acima ainda é necessário, mas você precisa lidar com a autorização.

 _locationManager = [CLLocationManager new]; _locationManager.delegate = self; _locationManager.distanceFilter = kCLDistanceFilterNone; _locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse //[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways ) { // Will open an confirm dialog to get user's approval [_locationManager requestWhenInUseAuthorization]; //[_locationManager requestAlwaysAuthorization]; } else { [_locationManager startUpdatingLocation]; //Will update location immediately } 

Este é o método delegado que manipula a autorização do usuário

 #pragma mark - CLLocationManagerDelegate - (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { switch (status) { case kCLAuthorizationStatusNotDetermined: { NSLog(@"User still thinking.."); } break; case kCLAuthorizationStatusDenied: { NSLog(@"User hates you"); } break; case kCLAuthorizationStatusAuthorizedWhenInUse: case kCLAuthorizationStatusAuthorizedAlways: { [_locationManager startUpdatingLocation]; //Will update location immediately } break; default: break; } } 

Você usa a estrutura CoreLocation para acessar informações de localização sobre seu usuário. Você precisará instanciar um object CLLocationManager e chamar a mensagem startUpdatingLocation assíncrona. Você receberá retornos de chamada com a localização do usuário por meio do CLLocationManagerDelegate fornecido.

Tente este simples passos ….

OBSERVAÇÃO: verifique a latitude e o logitude da localização do dispositivo se estiver usando meios de simulador. Por padrão, não é apenas.

Etapa 1: Importe a estrutura do CoreLocation no arquivo .h

 #import  

Etapa 2: adicionar delegado CLLocationManagerDelegate

 @interface yourViewController : UIViewController { CLLocationManager *locationManager; CLLocation *currentLocation; } 

Etapa 3: adicione este código no arquivo de class

 - (void)viewDidLoad { [super viewDidLoad]; [self CurrentLocationIdentifier]; // call this method } 

Etapa 4: Método para detectar a localização atual

 //------------ Current Location Address----- -(void)CurrentLocationIdentifier { //---- For getting current gps location locationManager = [CLLocationManager new]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; //------ } 

Etapa 5: obter a localização usando esse método

 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { currentLocation = [locations objectAtIndex:0]; [locationManager stopUpdatingLocation]; CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { if (!(error)) { CLPlacemark *placemark = [placemarks objectAtIndex:0]; NSLog(@"\nCurrent Location Detected\n"); NSLog(@"placemark %@",placemark); NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "]; NSString *Address = [[NSString alloc]initWithString:locatedAt]; NSString *Area = [[NSString alloc]initWithString:placemark.locality]; NSString *Country = [[NSString alloc]initWithString:placemark.country]; NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country]; NSLog(@"%@",CountryArea); } else { NSLog(@"Geocode failed with error %@", error); NSLog(@"\nCurrent Location Not Detected\n"); //return; CountryArea = NULL; } /*---- For more results placemark.region); placemark.country); placemark.locality); placemark.name); placemark.ocean); placemark.postalCode); placemark.subLocality); placemark.location); ------*/ }]; } 

No Swift (para iOS 8+).

Info.plist

Primeiras coisas primeiro. Você precisa adicionar sua string descritiva no arquivo NSLocationWhenInUseUsageDescription para as chaves NSLocationWhenInUseUsageDescription ou NSLocationAlwaysUsageDescription dependendo do tipo de serviço que você está solicitando

Código

 import Foundation import CoreLocation class LocationManager: NSObject, CLLocationManagerDelegate { let manager: CLLocationManager var locationManagerClosures: [((userLocation: CLLocation) -> ())] = [] override init() { self.manager = CLLocationManager() super.init() self.manager.delegate = self } //This is the main method for getting the users location and will pass back the usersLocation when it is available func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) { self.locationManagerClosures.append(userLocationClosure) //First need to check if the apple device has location services availabel. (ie Some iTouch's don't have this enabled) if CLLocationManager.locationServicesEnabled() { //Then check whether the user has granted you permission to get his location if CLLocationManager.authorizationStatus() == .NotDetermined { //Request permission //Note: you can also ask for .requestWhenInUseAuthorization manager.requestWhenInUseAuthorization() } else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied { //... Sorry for you. You can huff and puff but you are not getting any location } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { // This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available manager.startUpdatingLocation() } } } //MARK: CLLocationManager Delegate methods @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedAlways || status == .AuthorizedWhenInUse { manager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { //Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location. //These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array. let tempClosures = self.locationManagerClosures for closure in tempClosures { closure(userLocation: newLocation) } self.locationManagerClosures = [] } } 

Uso

 self.locationManager = LocationManager() self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in print(userLocation) } 

A Documentação do Xcode tem uma riqueza de conhecimento e exemplos de aplicativos – verifique o Guia de Programação de Consciência do Local .

O projeto de amostra LocateMe ilustra os efeitos da modificação das diferentes configurações de precisão do CLLocationManager

Você pode usar este serviço que eu escrevi para lidar com tudo para você.

Este serviço solicitará as permissions e lidará com o CLLocationManager para que você não precise fazer isso.

Use assim:

 LocationService.getCurrentLocationOnSuccess({ (latitude, longitude) -> () in //Do something with Latitude and Longitude }, onFailure: { (error) -> () in //See what went wrong print(error) }) 

O iOS 11.x Swift 4.0 Info.plist precisa dessas duas propriedades

 NSLocationAlwaysAndWhenInUseUsageDescription We're watching you NSLocationWhenInUseUsageDescription Watch Out 

E este código … certificando-se, claro, de um seu CLAocationManagerDelegate

 let locationManager = CLLocationManager() // MARK location Manager delegate code + more func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .notDetermined: print("User still thinking") case .denied: print("User hates you") case .authorizedWhenInUse: locationManager.stopUpdatingLocation() case .authorizedAlways: locationManager.startUpdatingLocation() case .restricted: print("User dislikes you") } 

E, claro, esse código também que você pode colocar em viewDidLoad ().

 locationManager.delegate = self locationManager.requestAlwaysAuthorization() locationManager.distanceFilter = kCLDistanceFilterNone locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestLocation() 

E estes dois para o requestLocation para você ir, aka salvar você ter que sair do seu lugar 🙂

 func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print(locations) }