objective-c ios8 mapkit cllocationmanager cllocation

objective c - MapKit da mal lat & lang-iOS 8



objective-c ios8 (4)

¡Sí! Tengo la solución, aquí está todo mi código y cosas agregadas para que funcione. Un agradecimiento especial a @MBarton por su gran ayuda. También gracias a @ Vinh Nguyen por invertir su valioso tiempo en resolver mi problema.

Se agregó el Marco de ubicación principal en Target-> General-> Linked Frameworks & Libraries

Agregado en el archivo .plist

NSLocationAlwaysUsageDescription

Ver captura de pantalla:

En mi ViewController.h

#import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <MapKit/MKAnnotation.h> #define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) @interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> { __weak IBOutlet UINavigationItem *navigationItem; } @property (weak, nonatomic) IBOutlet MKMapView *mapView; @property(nonatomic, retain) CLLocationManager *locationManager; @end

Luego en ViewController.m

#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize mapView; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self setUpMap]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)setUpMap { mapView.delegate = self; self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; #ifdef __IPHONE_8_0 if(IS_OS_8_OR_LATER) { // Use one or the other, not both. Depending on what you put in info.plist [self.locationManager requestAlwaysAuthorization]; } #endif [self.locationManager startUpdatingLocation]; mapView.showsUserLocation = YES; [mapView setMapType:MKMapTypeStandard]; [mapView setZoomEnabled:YES]; [mapView setScrollEnabled:YES]; } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:YES]; self.locationManager.distanceFilter = kCLDistanceFilterNone; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; [self.locationManager startUpdatingLocation]; NSLog(@"%@", [self deviceLocation]); //View Area MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } }; region.center.latitude = self.locationManager.location.coordinate.latitude; region.center.longitude = self.locationManager.location.coordinate.longitude; region.span.longitudeDelta = 0.005f; region.span.longitudeDelta = 0.005f; [mapView setRegion:region animated:YES]; } - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800); [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES]; } - (NSString *)deviceLocation { return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude]; }

Ufff ...! Obtuve la solución después de luchar con muchos códigos desde los últimos 5 días ...

Referido desde aquí

Cuando trato de usar el mapa en iOS 8, obtengo el siguiente error.

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

Para esto probé una solución desde aquí , pero todavía no tuve suerte.

Debajo está lo que hice.

Paso 1. Tener entrada en Info.plist

NSLocationWhenInUseUsageDescription - This is test text

Paso 2. Actualizado - (CLLocationCoordinate2D) getLocation

-(CLLocationCoordinate2D) getLocation{ CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; // this is change if(IS_OS_8_OR_LATER) { [locationManager requestWhenInUseAuthorization]; } [locationManager startUpdatingLocation]; CLLocation *location = [locationManager location]; CLLocationCoordinate2D coordinate = [location coordinate]; return coordinate; }

Paso 3. Prefix.pch

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

Paso 4. Elimina la aplicación de nuevo con la siguiente información en viewDidLoad.

CLLocationCoordinate2D theCoordinate; theCoordinate = [self getLocation]; NSLog(@"ffffff===%f===%f", theCoordinate.latitude, theCoordinate.longitude);

Todavía obtengo salida como

ffffff===0.000===0.000

Nota:

Recibo una advertencia, pero eso es solo por medio segundo y desaparece y luego recibo un mensaje como

CLLocationCoordinate2D theCoordinate; theCoordinate = [self getLocation]; NSLog(@"ffffff===%f===%f", theCoordinate.latitude, theCoordinate.longitude);

Cuando ingreso para verificar el estado de la ubicación, a continuación aparece lo que tengo.

¿Alguna idea de por qué está pasando esto?

Estoy probando en iPad 2 iOS 8.0 y simulador iOS 8.0


Debe implementar el delegado CLLocationManager (- (void) locationManager: (CLLocationManager *) administrador didUpdateLocations: (NSArray *) ubicaciones) para obtener actualizaciones de ubicación.

Aquí hay un fragmento de código para su referencia:

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

Alternativamente, puede implementar el siguiente método delegado de Mapkit:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { MKUserLocation *myLocation = userLocation; NSLog(@"ffffff===%f===%f", myLocation.coordinate.latitude, myLocation.coordinate.longitude); }


La requestWhenInUseAuthorization ejecuta de forma asíncrona, por lo que no debe llamar a startUpdatingLocation hasta que obtenga un cambio en el estado de la autorización en su delegado.


No estoy seguro de cuál fue el verdadero problema, pero poner el código siguiente en viewDidLoad resuelve el problema.

mapView.delegate = self; locationManager.delegate = self; self.locationManager = [[CLLocationManager alloc] init]; #ifdef __IPHONE_8_0 if(IS_OS_8_OR_LATER) { // Use one or the other, not both. Depending on what you put in info.plist [self.locationManager requestWhenInUseAuthorization]; } #endif [self.locationManager startUpdatingLocation]; mapView.showsUserLocation = YES; [mapView setMapType:MKMapTypeStandard]; [mapView setZoomEnabled:YES]; [mapView setScrollEnabled:YES];

Referencia