2011-06-29 15 views
34

Necesito encontrar mi ubicación actual con CoreLocation, probé varios métodos pero hasta ahora mi CLLocationManager solo ha devuelto 0's .. (0.000.00.000).Cómo encontrar su ubicación actual con CoreLocation

Aquí está mi código (actualizado para trabajar):

importaciones:

#import <CoreLocation/CoreLocation.h> 

Declarado:

IBOutlet CLLocationManager *locationManager; 
IBOutlet UILabel *latLabel; 
IBOutlet UILabel *longLabel; 

Funciones:

- (void)getLocation { //Called when needed 
    latLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude]; 
    longLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude]; 
} 

- (void)viewDidLoad { 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move 
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m 
    [locationManager startUpdatingLocation]; 
} 

Respuesta

77

Usted puede encontrar su ubicación mediante CoreLocation así:

importación CoreLocation:

#import <CoreLocation/CoreLocation.h> 

Declarar CLLocationManager:

CLLocationManager *locationManager; 

inicializar el locationManager en viewDidLoad y crear una función que puede return la ubicación actual como una NSString:

- (NSString *)deviceLocation { 
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude]; 
} 

- (void)viewDidLoad 
{ 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move 
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m 
    [locationManager startUpdatingLocation]; 
} 

Y llamando a la función deviceLocation devolverá la ubicación como se esperaba:

NSLog(@"%@", [self deviceLocation]); 

Esto es sólo un ejemplo. Inicializar CLLocationManager sin que el usuario esté listo para hacerlo no es una buena idea. Y, por supuesto, locationManager.location.coordinate se puede utilizar para obtener latitude y longitude a voluntad después de que se haya inicializado CLLocationManager.

No olvide agregar CoreLocation.framework en la configuración de su proyecto en la pestaña Crear fases (Targets->Build Phases->Link Binary).

+0

Pero este método ya no devuelve la ubicación actual. Estoy usando Xcode 6. Pero funcionó bien cuando usé Xcode 5. – SARATH

15

Con CLLocationManager no es necesario obtener la información de ubicación inmediatamente. Es posible que el GPS y otros dispositivos que obtienen información de ubicación no se hayan inicializado. Pueden tomar un tiempo antes de que tengan información. En su lugar, debe crear un objeto delegado que responda al locationManager:didUpdateToLocation:fromLocation: y luego configurarlo como el delegado del administrador de ubicación.

ver here

+2

Este artículo http: // mobileorchard.com/hello-there-a-corelocation-tutorial/(tomado de una pregunta relacionada con stackoverflow) muestra qué hacer. – ThomasW

-2

Aquí se puede mostrar la ubicación actual con detalles de anotación

en ViewController.h

#import <UIKit/UIKit.h> 
#import <CoreLocation/CoreLocation.h> 


//My 
#import <MapKit/MapKit.h> 
#import <MessageUI/MFMailComposeViewController.h> 

@interface ViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,MFMailComposeViewControllerDelegate> 
{ 
    IBOutlet UILabel *lblLatitiude; 
    IBOutlet UILabel *lblLongitude; 
    IBOutlet UILabel *lblAdress; 
} 
//My 
@property (nonatomic, strong) IBOutlet MKMapView *mapView; 


-(IBAction)getMyLocation:(id)sender; 

@end 

en ViewController.m

#import "ViewController.h" 


@interface ViewController() 

@end 

@implementation ViewController{ 
    CLLocationManager *locationManager; 
    CLGeocoder *geocoder; 
    CLPlacemark *placemark; 
} 

@synthesize mapView; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    locationManager = [[CLLocationManager alloc] init]; 
    geocoder = [[CLGeocoder alloc] init]; 

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
    NSMutableDictionary *defaultsDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"[email protected]", @"fromEmail", 
               @"[email protected]", @"toEmail", 
               @"smtp.gmail.com", @"relayHost", 
               @"[email protected]", @"login", 
               @"[email protected]", @"pass", 
               [NSNumber numberWithBool:YES], @"requiresAuth", 
               [NSNumber numberWithBool:YES], @"wantsSecure", nil]; 

    [userDefaults registerDefaults:defaultsDictionary]; 


    self.mapView.delegate=self; 

} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Custom Methods 


-(IBAction)getMyLocation:(id)sender{ 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

    [locationManager startUpdatingLocation]; 
} 


#pragma mark - CLLocationManagerDelegate 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
    NSLog(@"didFailWithError: %@", error); 
    UIAlertView *errorAlert = [[UIAlertView alloc] 
           initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [errorAlert show]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    NSLog(@"didUpdateToLocation: %@", newLocation); 
    CLLocation *currentLocation = newLocation; 

    if (currentLocation != nil) { 
     lblLongitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
     lblLatitiude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 
    } 

    // Stop Location Manager 
    [locationManager stopUpdatingLocation]; 

    // Reverse Geocoding 
    NSLog(@"Resolving the Address"); 
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { 
     NSLog(@"Found placemarks: %@, error: %@", placemarks, error); 
     if (error == nil && [placemarks count] > 0) { 
      placemark = [placemarks lastObject]; 

      lblAdress.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@", 
           placemark.subThoroughfare, placemark.thoroughfare, 
           placemark.postalCode, placemark.locality, 
           placemark.administrativeArea, 
           placemark.country]; 



      MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate, 800, 800); 
      [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES]; 

      // Add an annotation 
      MKPointAnnotation *point = [[MKPointAnnotation alloc] init]; 
      point.coordinate = currentLocation.coordinate; 
      point.title = @"Where am I?"; 
      point.subtitle = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@", 
           placemark.subThoroughfare, placemark.thoroughfare, 
           placemark.postalCode, placemark.locality, 
           placemark.administrativeArea, 
           placemark.country]; 


      [self.mapView addAnnotation:point]; 


     } else { 
      NSLog(@"%@", error.debugDescription); 
     } 
    } ]; 


} 

//My 
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"]; 
    annotationView.canShowCallout = YES; 
    annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 

    return annotationView; 
} 

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control 
{ 

    [self getSignScreenShot]; 

    MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init]; 
    controller.mailComposeDelegate = self; 
    [controller setSubject:@"My Subject"]; 
    [controller setMessageBody:@"Hello there." isHTML:NO]; 
    if (controller) [self presentModalViewController:controller animated:YES]; 
} 

- (void)mailComposeController:(MFMailComposeViewController*)controller 
      didFinishWithResult:(MFMailComposeResult)result 
         error:(NSError*)error; 
{ 
    if (result == MFMailComposeResultSent) { 
     NSLog(@"It's away!"); 
    } 
    [self dismissModalViewControllerAnimated:YES]; 
} 

//----------------------------------------------------------------------------------- 
//This methos is to take screenshot of map 
//----------------------------------------------------------------------------------- 
-(UIImage *)getSignScreenShot 
{ 
    CGRect rect = CGRectMake(self.mapView.frame.origin.x,self.mapView.frame.origin.y-50,self.mapView.frame.size.width+60,self.mapView.frame.size.height+15); 
    UIGraphicsBeginImageContextWithOptions(self.mapView.frame.size, NO, 1.0); 
    [self.mapView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); 
    CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], rect); 
    UIImage *newImage = [UIImage imageWithCGImage:imageRef]; 

    return newImage; 
} 
Cuestiones relacionadas