I have made one demo for getting Current Location.
I have used .GPX file for my current Location.
I have used Delegates method of CLLocation Method.
I have Also use Key "Privacy - Location When In Use Usage Description" in my plist file.
I know this question already asked so many time but could not able to get result.
code is
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
#property (nonatomic,assign)CLLocationCoordinate2D cordinateLocation;
#property (nonatomic,strong)MKPointAnnotation *point;
#property (nonatomic,weak)IBOutlet MKMapView *mapView;
#end
#implementation ViewController
CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
self.mapView.delegate = self;
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
//-(void)getCurrentLocation
//{
// [locationManager requestWhenInUseAuthorization];
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// [locationManager startUpdatingHeading];
// [locationManager startUpdatingLocation];
//
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertController *errorAlert =[UIAlertController alertControllerWithTitle:#"Error" message:#"error reported" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertStyle = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[errorAlert addAction:alertStyle];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *updatedLocation = [locations lastObject];
if(updatedLocation != nil)
{
self.cordinateLocation=CLLocationCoordinate2DMake(updatedLocation.coordinate.latitude, updatedLocation.coordinate.longitude);
[manager stopUpdatingLocation];
[self setCurrentLocationFocus];
}
else{
NSLog(#"Can't access desire location");
}
}
-(void)setCurrentLocationFocus{
MKCoordinateRegion region;
region.center = self.cordinateLocation;
//Adjust span as you like
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
///Drop the pin on Current Locatio ////
self.point = [[MKPointAnnotation alloc] init];
self.point.coordinate = self.cordinateLocation;
self.point.title = #"FlockStation";
self.point.subtitle = #"It Department";
[self.mapView addAnnotation:self.point];
//set a new camera angle
MKMapCamera *newCamera=[[MKMapCamera alloc] init];
[newCamera setCenterCoordinate:self.cordinateLocation];
[newCamera setPitch:60.0]; ///For zooming purpose///
[newCamera setHeading:90]; ///For Compass Purpose ///
[newCamera setAltitude:100.0]; ///On which height you want to see your map ///
[self.mapView setCamera:newCamera animated:YES];
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"NewViewController"];
[self presentViewController:viewController animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// self.updatedHeading.text = [NSString stringWithFormat:#"%f",newHeading.magneticHeading];
}
Help Me guys not able to get location.Because delegates method is not calling.
Every Time it called this method.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:`(NSError *)error
You need to check permission of location. then after you can call the delegate methods.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManager requestWhenInUseAuthorization];
}
if ([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:#"Permission Denied"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
txtlocations.text = [NSString stringWithFormat:#"%f & %f",currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
}
Tried with your code with little changes and its working fine.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
if([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager requestWhenInUseAuthorization];
[locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
// show the map
} else {
// show error
}
}
Related
I have to find the current location and i am using this code
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
but latitude and longitude is coming zero? and i have called these method in viewDidLoad
[self getCurrentLocation];
[self getLocation];
why is it so please help me. thanks
I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
#end
and add this:
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];
Callback function
- (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);
}
You also have to add a string for the
[`NSLocationAlwaysUsageDescription`]
You need to use "CLLocationManagerDelegate".
Just go through this tutorial. How To Get the User Location in iPhone App
Here you will learn about CoreLocation Framework.
This is the delegate method which will return you current lat-long.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
And also make sure your app authorize to use location services.
And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.
Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.
Step 2 : Make sure your view-controller implement CLLocationManagerDelegate
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
Step 3 : Define class instance of CLLocationManager
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
Step 4 :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
//iOS 8.0 onwards
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
Step 5 : Here is your CLLocationManagerDelegate
method implementation
- (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) {
NSLog(#"Longitude %.8f",currentLocation.coordinate.longitude);
NSLog(#"Latitude %.8f",currentLocation.coordinate.latitude);
}
}
First go to your info.plist and right click on it and select the source code option.
Then add the following lines after the <dict> keyword
<key>NSLocationAlwaysUsageDescription</key>
<string>This App wants to Know your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This App wants to Know your location</string>
Without this, you can't get CLLocation working in iOS 9.0.
Now follow the instruction.
Import
#import <CoreLocation/CoreLocation.h>
and list the CoreLocation delegate like
#interface ViewController ()<CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
Then in the viewDidLoad method add the following lines-
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Now implement the delegate methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Sorry"
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) {
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.longitude]);
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.latitude]);
}
}
It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.
Well, I wanted you to read the doc, still I am posting the solution.
-(void)viewDidLoad{
[self initLocationManager];
}
-(void)initLocationManager{
self.locationManager=[[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if (([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
[_locationManager requestWhenInUseAuthorization];
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}
Then handle the location updates in the CLLocationManager delegate method like below
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
NSLog(#"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
}
}
Update
To make it work, you need to do two things
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
Use this code it works
firstly add NSLocationAlwaysUsageDescription as string in info.plist
in .h
#import <CoreLocation/CoreLocation.h>
#interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
#end
in .m use this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager . delegate = self;
[self initLocationManager];
}
-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(#"Current Coordinates are %f,%f",location.coordinate.latitude,location.coordinate.longitude);
[locationManager stopUpdatingLocation];
}
}
it will give output like
[2390:96060] Current Coordinates are 37.332331,-122.031219
I have to find the current location and i am using this code
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
but latitude and longitude is coming zero? and i have called these method in viewDidLoad
[self getCurrentLocation];
[self getLocation];
why is it so please help me. thanks
I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
#end
and add this:
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];
Callback function
- (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);
}
You also have to add a string for the
[`NSLocationAlwaysUsageDescription`]
You need to use "CLLocationManagerDelegate".
Just go through this tutorial. How To Get the User Location in iPhone App
Here you will learn about CoreLocation Framework.
This is the delegate method which will return you current lat-long.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
And also make sure your app authorize to use location services.
And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.
Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.
Step 2 : Make sure your view-controller implement CLLocationManagerDelegate
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
Step 3 : Define class instance of CLLocationManager
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
Step 4 :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
//iOS 8.0 onwards
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
Step 5 : Here is your CLLocationManagerDelegate
method implementation
- (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) {
NSLog(#"Longitude %.8f",currentLocation.coordinate.longitude);
NSLog(#"Latitude %.8f",currentLocation.coordinate.latitude);
}
}
First go to your info.plist and right click on it and select the source code option.
Then add the following lines after the <dict> keyword
<key>NSLocationAlwaysUsageDescription</key>
<string>This App wants to Know your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This App wants to Know your location</string>
Without this, you can't get CLLocation working in iOS 9.0.
Now follow the instruction.
Import
#import <CoreLocation/CoreLocation.h>
and list the CoreLocation delegate like
#interface ViewController ()<CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
Then in the viewDidLoad method add the following lines-
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Now implement the delegate methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Sorry"
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) {
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.longitude]);
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.latitude]);
}
}
It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.
Well, I wanted you to read the doc, still I am posting the solution.
-(void)viewDidLoad{
[self initLocationManager];
}
-(void)initLocationManager{
self.locationManager=[[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if (([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
[_locationManager requestWhenInUseAuthorization];
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}
Then handle the location updates in the CLLocationManager delegate method like below
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
NSLog(#"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
}
}
Update
To make it work, you need to do two things
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
Use this code it works
firstly add NSLocationAlwaysUsageDescription as string in info.plist
in .h
#import <CoreLocation/CoreLocation.h>
#interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
#end
in .m use this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager . delegate = self;
[self initLocationManager];
}
-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(#"Current Coordinates are %f,%f",location.coordinate.latitude,location.coordinate.longitude);
[locationManager stopUpdatingLocation];
}
}
it will give output like
[2390:96060] Current Coordinates are 37.332331,-122.031219
I have a MapViewController that imports SWRevealViewController and I honestly didn't code this lines below. I tried to run the app but unfortunately the map is not showing the current location and even the location service does not get turn on the phone even the app is granted permission to access GPS. Since i'm not a expect in iOS development I need someone to look the code and explain what is missing in this code. I looked at similar question but they seem straight forward even for someone learning objective-c. The problem with this code i assume is the SWRevealViewController imported here, which I think is a library or something i don't know.
#import "MapViewController.h"
#import "SWRevealViewController.h"
// New York
#define NY_LATITUDE 40.754445
#define NY_LONGITUDE -73.977364
// Span and distance
#define SPAN_VALUE 1.0f
#define DISTANCE 500
#interface MapViewController ()
- (void)startLocationServices;
- (void)stopLocationServices;
#end
#implementation MapViewController
#synthesize locationManager;
#synthesize gpsDisplay;
#synthesize mapk;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)sendRequest:(id)sender {
[self alertStatus:#"An assistance request has been sent, you will be contacted shortly." :#"Send assistance request" :0];
[self performSegueWithIdentifier:#"sendRequest" sender:nil];
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex
{
if(buttonIndex==0)
{
//NSLog(#"OK Clicked");
// [self alertStatus:#"An assistance request has been sent, you will be contacted shortly. " :#"I just had an accident" :0];
// [self performSegueWithIdentifier:#"checkProgress" sender:nil];
}}
- (void)viewDidLoad
{
[super viewDidLoad];
[self startLocationServices];
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
} else {
NSLog(#"Location services are not enabled");
}
// Set a timer to stop the Location services
//[NSTimer scheduledTimerWithTimeInterval:100.0 target:self selector:#selector(stopLocationServices) userInfo:nil repeats:NO];
_sidebarButton.tintColor = [UIColor colorWithWhite:0.1f alpha:0.9f];
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
// CLLocationManager *cllocationManager = [[CLLocationManager alloc] init];
// cllocationManager.delegate = self;
// cllocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
// cllocationManager.distanceFilter = 20.0f;
//
// if ([CLLocationManager locationServicesEnabled])
// {
// [cllocationManager startUpdatingLocation];
// }
// else
// {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Turn On Location Services to find your location"
// message:nil delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
// // [alert release];
// }
}
- (IBAction)mapChanger:(id)sender {
switch (((UISegmentedControl *) sender).selectedSegmentIndex) {
case 0:
self.mapk.mapType = MKMapTypeStandard;
break;
case 1:
self.mapk.mapType = MKMapTypeSatellite;
break;
case 2:
self.mapk.mapType = MKMapTypeHybrid;
break;
default:
break;
}
}
- (void)startLocationServices
{
// create the Location Manager
if (self.locationManager == nil) {
self.locationManager = [CLLocationManager new];
}
// settings
[self.locationManager setDelegate:self];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
// start services
[self.locationManager startUpdatingLocation];
self.gpsDisplay.text = #"Location Service started.";
}
- (void)stopLocationServices
{
// stop services
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
self.gpsDisplay.text = #"Location Services stopped.";
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocationCoordinate2D loc = [userLocation coordinate];
// CLLocationDistance in meters (1 meter = 3.3 feet)
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, DISTANCE, DISTANCE);
[mapView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSString *coords =#"lat";
coords = [coords stringByAppendingString:[NSString stringWithFormat:#"%f", newLocation.coordinate.latitude]];
coords = [coords stringByAppendingString:#"lon"];
coords = [coords stringByAppendingString:[NSString stringWithFormat:#"%f", newLocation.coordinate.longitude]];
self.gpsDisplay.text = coords;
MKCoordinateRegion region;
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude = newLocation.coordinate.longitude;
region.span.latitudeDelta = SPAN_VALUE;
region.span.longitudeDelta = SPAN_VALUE;
[self.mapk setRegion:region animated:YES];
}
- (void)viewDidUnload {
//[self setUpdates:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
In addition to the previous answer, note that you have to specify the reason for accessing the user's location information adding the relative key (NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription) to your project's Info.plist
for example:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is required to find out jobs around you are</string>
On iOS 8, they changed how you ask for location permission. Instead of just being able to call startUpdatingLocation you need to now call either requestWhenInUseAuthorization or requestAlwaysAuthorization.
i want to find the current location of the user
below the code for finding coordinates from the well defined adress
hom can i find the current location of the user ..please help me
.h file
#import
#import
#interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
#property(nonatomic,retain) MKMapView *myMapView;
#property (nonatomic, strong) CLGeocoder *myGeocoder;
#end
.m file
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface ViewController ()
{
CLLocationManager *locationManager;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.myMapView.showsUserLocation=YES;
self.view.backgroundColor=[UIColor whiteColor];
self.myMapView=[[MKMapView alloc]initWithFrame:self.view.bounds];
self.myMapView.mapType=MKMapTypeHybrid;
self.myMapView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myMapView];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSString *oreillyAddress =#"india";
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder
geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0 && error == nil)
{
NSLog(#"Found %lu placemark(s).", (unsigned long)[placemarks count]);
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0]; NSLog(#"Longitude = %f", firstPlacemark.location.coordinate.longitude); NSLog(#"Latitude = %f", firstPlacemark.location.coordinate.latitude);
}
else if ([placemarks count] == 0 &&
error == nil){ NSLog(#"Found no placemarks.");
}
else if (error != nil){
NSLog(#"An error occurred = %#", error); }
}];
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
float latitude=newLocation.coordinate.latitude;
float longitude=newLocation.coordinate.longitude;
NSLog(#"%f",latitude);
NSLog(#"%f",longitude);
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"error==>%#",error);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Define
CLLocationManager *lm;
CLLocation *location;
and then add the below mentioned code in your ViewDidLoad method
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
lm.distanceFilter = kCLDistanceFilterNone;
[lm startUpdatingLocation];
location = [lm location];
CLLocationCoordinate2D coordinate;
coordinate.longitude = location.coordinate.longitude;
coordinate.latitude = location.coordinate.latitude;
if((location.coordinate.longitude== 0.0 ) && (location.coordinate.latitude==0.0))
{
UIAlertView *alert2 = [[UIAlertView alloc ] initWithTitle:(#"Server Error:")message:(#"Internet Problem. Try Later !!!") delegate:nil cancelButtonTitle:nil otherButtonTitles:(#"OK"), nil];
[alert2 show];
}
else
{
coordinate = [location coordinate];
NSLog(#"Latitude of User is %f",coordinate.longitude);
NSLog(#"Longitude of User is %f",coordinate.latitude);
}
Use this
self.myMapView.showsUserLocation = YES;
If you are using the simulator, you would need to go to: Debug -> Location -> Customer. From there set your location to the desired test point.
To get user's current location in iOS 8
Add <CLLocationManagerDelegate> in .h file.
CLLocationManager *locationManager;
CLLocation *currentLocation;
locationManager = [CLLocationManager new];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse)
{
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
NSString *currentLatitude = [NSString stringWithFormat:#"%f",location.coordinate.latitude];
NSString *currentLongitude = [NSString stringWithFormat:#"%f",location.coordinate.longitude];
[locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status)
{
case kCLAuthorizationStatusNotDetermined:
case kCLAuthorizationStatusRestricted:
case kCLAuthorizationStatusDenied:
{
[locationManager requestAlwaysAuthorization];
}
break;
default:
{
[locationManager startUpdatingLocation];
}
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"Error while getting core location : %#",[error localizedFailureReason]);
if ([error code] == kCLErrorDenied)
{
//you had denied
}
[manager stopUpdatingLocation];
}
And In your plist file Dont forget to Enter a key
NSLocationAlwaysUsageDescription
Use this:
[self.mapview setShowsUserLocation:YES];
I want to get the coordinates of the user, once user starts the app it should initialise GPS coordinates. I have followed this tutorial:
http://www.iosdevnotes.com/2011/10/ios-corelocation-tutorial/
I have created a class named CurrentLocationWithGPS
This is the header:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
- (void) getLocations;
- (Float32) latitude;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLLocation *currentLocation;
#end
This is the implementation:
#import "CurrentLocationWithGPS.h"
#implementation CurrentLocationWithGPS
#synthesize locationManager, currentLocation;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if(error.code == kCLErrorDenied) {
[locationManager stopUpdatingLocation];
} else if(error.code == kCLErrorLocationUnknown) {
// retry
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error retrieving location"
message:[error description]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void) getLocations {
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
- (Float32) latitude {
return currentLocation.coordinate.latitude;
}
- (Float32) longitude {
return currentLocation.coordinate.longitude;
}
#end
I call the getLocations function in a separate thread so that it wouldn't block anything else. Here is how I call it from another class:
- (void)viewDidLoad
{
[super viewDidLoad];
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:#selector(locationSet) object:nil];
[myThread start];
}
- (void) locationSet {
CurrentLocationWithGPS *locationFind = [[CurrentLocationWithGPS alloc] init];
locationFind.getLocations;
NSLog(#"latitude is %f", locationFind.latitude);
}
Now the problem is both latitude and longitdute functions are returning 0.000, what am I missing here? I am developing for iOS6.1.
First conforms CLLocationManagerDelegate in .h file like this
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
You need to set CLLocation's Delegate in this method.
- (void) getLocations
{
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
Do you getting the Current Location on the output . Or R you just trying to retrieve the Co-ordinates ?..
It's still confusing , anyhow
Put this part of code on Your getLocations method
I Hope that You are not at all checking with Location Services . You
Should enable the LocationServices for your app else You always get
null values Check with the Condition:
if ([CLLocationManager locationServicesEnabled])
{
}
For Example :
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
And Let me know , .????