ubicacion rastrear puedo perdido otro localizar localizacion internet desde dejar compartir como buscar activar iphone objective-c cllocationmanager currentlocation

iphone - rastrear - ¿Cómo puedo obtener la ubicación actual del usuario en iOS?



no puedo activar localizacion iphone (7)

¿Cómo puedo obtener la ubicación actual del usuario en iOS?


En Swift (para iOS 8+).

Info.plist

Lo primero es lo primero. Debe agregar su cadena descriptiva en el archivo info.plist para las claves NSLocationWhenInUseUsageDescription o NSLocationAlwaysUsageDescription dependiendo del tipo de servicio que 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. (i.e. 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) }


Prueba este Simple Steps ....

NOTA: compruebe la latitud y la lentitud de la ubicación del dispositivo si está utilizando medios de simulación. Por defecto, no es solo.

Paso 1: Importar la estructura de CoreLocation en archivo .h

#import <CoreLocation/CoreLocation.h>

Paso 2: Agregar delegado CLLocationManagerDelegate

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

Paso 3: agrega este código en el archivo de clase

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

Paso 4: Método para detectar la ubicación actual

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

Paso 5: obtener ubicación usando este 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); ------*/ }]; }


En iOS 6, el

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

es obsoleto.

Use el siguiente código en su lugar

- (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, el método anterior aún es necesario, pero debe manejar la autorización.

_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 es el método delegado que maneja la autorización del usuario

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



La respuesta de RedBlueThing funcionó bastante bien para mí. Aquí hay un código de muestra de cómo lo hice.

Encabezamiento

#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface yourController : UIViewController <CLLocationManagerDelegate> { CLLocationManager *locationManager; } @end

Archivo principal

En el método init

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

Función de devolución de llamada

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

En iOS 6, la función de delegado quedó en desuso. El nuevo delegado es

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

Por lo tanto, para obtener el nuevo uso de la posición

[locations lastObject]

iOS 8

En iOS 8, se debe solicitar explícitamente el permiso antes de comenzar a actualizar la ubicación

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

También debe agregar una cadena para las claves NSLocationAlwaysUsageDescription o NSLocationAlwaysUsageDescription a la aplicación Info.plist. De lo contrario, las llamadas a startUpdatingLocation se ignorarán y su delegado no recibirá ninguna devolución de llamada.

Y al final, cuando haya terminado de leer la ubicación, llame a stopUpdating ubicación en el lugar adecuado.

[locationManager stopUpdatingLocation];


Puede usar este servicio que escribí para manejar todo por usted.

Este servicio solicitará los permisos y manejará el trato con CLLocationManager para que no tenga que hacerlo.

Use esto:

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