Tutorial iOS – Recuperando a localização do usuário utilizando CoreLocation
Nesse tutorial iremos aprender a fazer um app que recupera as informações de localização do usuário. Para isso utilizaremos o framework disponibilizado pela apple no kit de desenvolvimento chamado CoreLocation. Para isso devemos seguir os seguintes passos:
1 – Crie uma Single View Based Aplication
2 – Em seu projeto vá em General > Linked Frameworks and Libraries e adicione CoreLocation.framework
4 – Faça as seguintes alterações em ViewController.h
[sourcecode language=”java”]
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController{
IBOutlet UILabel *latitude;
IBOutlet UILabel *longitude;
IBOutlet UILabel *altitude;
IBOutlet UILabel *speed;
CLLocationManager *locationManager;
}
@end
[/sourcecode]
Obs: Esses label irão receber os dados do usuário.
5 – Faça as seguintes alterações no ViewController.m
[sourcecode language=”java”]
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc]init]; // initializing locationManager
locationManager.delegate = self; // we set the delegate of locationManager to self.
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy
[locationManager startUpdatingLocation]; //requesting location updates
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"There was an error retrieving your location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[errorAlert show];
NSLog(@"Error: %@",error.description);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *crnLoc = [locations lastObject];
latitude.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.latitude];
longitude.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.longitude];
altitude.text = [NSString stringWithFormat:@"%.0f m",crnLoc.altitude];
speed.text = [NSString stringWithFormat:@"%.1f m/s", crnLoc.speed];
}
@end
[/sourcecode]
6 -Adicione as label declaradas no ViewController.h ao storyboard e linke cada uma.
RESULTADO
Rode o aplicativo e você vera as informações, sendo elas latitude, longitude, altitude e velocidade.