Come posso ottenere la posizione corrente dall’utente in iOS

Come posso ottenere la posizione corrente dall’utente in iOS?

La risposta di RedBlueThing ha funzionato abbastanza bene per me. Ecco alcuni esempi di come l’ho fatto.

Intestazione

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

mainfile

Nel metodo init

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

Funzione di callback

 - (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

In iOS 6 la funzione delegato è stata ritirata. Il nuovo delegato è

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

Quindi per usare la nuova posizione

 [locations lastObject] 

iOS 8

In iOS 8 l’authorization dovrebbe essere esplicitamente richiesta prima di iniziare ad aggiornare la posizione

 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]; 

È inoltre necessario aggiungere una stringa per le chiavi NSLocationAlwaysUsageDescription o NSLocationWhenInUseUsageDescription dell’app. In caso contrario, le chiamate a startUpdatingLocation verranno ignorate e il delegato non riceverà alcuna richiamata.

E alla fine, quando hai finito di leggere la posizione, chiama stopUpdating location at suitable place.

 [locationManager stopUpdatingLocation]; 

In iOS 6, il

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

è deprecato.

Usa invece il seguente codice

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

Per iOS 6 ~ 8, il metodo sopra è ancora necessario, ma devi gestire l’authorization.

 _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 } 

Questo è il metodo delegato che gestisce l’authorization dell’utente

 #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; } } 

Si utilizza la struttura CoreLocation per accedere alle informazioni sulla posizione dell’utente. Sarà necessario creare un’istanza di un object CLLocationManager e chiamare il messaggio di startUpdatingLocation asincrono. Riceverai i callback con la posizione dell’utente tramite CLLocationManagerDelegate che fornisci.

Prova questa semplice procedura ….

NOTA: Si prega di verificare la latitudine e la logitudine della posizione del dispositivo se si utilizzano i mezzi del simulatore. Di default non ne ha solo.

Passaggio 1: importare il framework CoreLocation nel file .h

 #import  

Passaggio 2: Aggiungi delegato CLLocationManagerDelegate

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

Passaggio 3: aggiungi questo codice nel file di class

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

Passaggio 4: metodo per rilevare la posizione corrente

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

Passaggio 5: ottenere la posizione utilizzando questo metodo

 - (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); ------*/ }]; } 

In Swift (per iOS 8+).

Info.plist

Cominciando dall’inizio. È necessario aggiungere la stringa descrittiva nel file info.plist per le chiavi NSLocationWhenInUseUsageDescription o NSLocationAlwaysUsageDescription seconda del tipo di servizio che si richiede

Codice

 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) } 

La documentazione di Xcode ha una vasta gamma di informazioni e app di esempio: consulta la Guida alla programmazione di sensibilizzazione sulla posizione .

Il progetto di esempio LocateMe illustra gli effetti della modifica delle diverse impostazioni di accuratezza di CLLocationManager

Puoi usare questo servizio che ho scritto per gestire tutto per te.

Questo servizio richiederà le autorizzazioni e gestirà il trattamento con CLLocationManager in modo da non doverlo fare.

Usa in questo modo:

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

iOS 11.x Swift 4.0 Info.plist ha bisogno di queste due proprietà

 NSLocationAlwaysAndWhenInUseUsageDescription We're watching you NSLocationWhenInUseUsageDescription Watch Out 

E questo codice … assicurandoti ovviamente che tu sia un CLLocationManagerDelegate

 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 ovviamente anche questo codice che puoi inserire in viewDidLoad ().

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

E questi due per la richiestaLa posizione per farti andare avanti, ovvero risparmiare il fatto che devi uscire dal tuo posto 🙂

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