user6438311 user6438311 - 5 months ago 50
Objective-C Question

How to get current location in ios in simulator?

i am using this code to get current location but not getting the correct result to get the current location in simulator,

-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate = self;
if (([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;

//[locationManager requestWhenInUseAuthorization];
// [locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
// NSDate* eventDate = location.timestamp;
// NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];

latitud = location.coordinate.latitude;
longitud = location.coordinate.longitude;
NSLog(@"%f,%f",latitud,longitud);
[locationManager stopUpdatingLocation];

}


please tell me how to get this current location, i am getting tired trying this from the morning. please help me

Answer

Create a GPX file by using following steps:

  • Go in project--> Add new --> iOS -- > Resource and select GPX file

enter image description here

  • Now you need to do small code in to GPX file as following:

<!--
        Provide one or more waypoints containing a latitude/longitude pair. If you provide one
        waypoint, Xcode will simulate that specific location. If you provide multiple waypoints,
        Xcode will simulate a route visitng each waypoint.
 -->
<wpt lat="37.331705" lon="-122.030237">  // here change lat long to your lat long
     <name>Cupertino</name> // here set name 

     <!--   
            Optionally provide a time element for each waypoint. Xcode will interpolate movement
            at a rate of speed based on the time elapsed between each waypoint. If you do not provide
            a time element, then Xcode will use a fixed rate of speed.

            Waypoints must be sorted by time in ascending order.
      -->
     <time>2014-09-24T14:55:37Z</time>
</wpt>

  • Now go to edit schema

    enter image description here

  • And select run and do in Option menu select like following there is appear our GPX file select that and run and close:

enter image description here

That's it now you can get location of your added lat long in GPX file.

UPDATE

Following is a code for enable location:

  • In info.plist you need set NSLocationWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription about location services.

NSLocationWhenInUseUsageDescription

Now your .h class

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<CLLocationManagerDelegate>
{

    __weak IBOutlet UILabel *lblLat;
    __weak IBOutlet UILabel *lblLong;
}
@property(strong,nonatomic) CLLocationManager *locationManager;
@end

.M class

- (void)viewDidLoad {
    [super viewDidLoad];

    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager requestWhenInUseAuthorization];


    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [self.locationManager startUpdatingLocation];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (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) {
        lblLat.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
        lblLong.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    }
}

Working demo code: https://github.com/nitingohel/UserCurrentLocation_Objc