How to Get Current Location from User in Ios

How can I get current location from user in iOS

The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.

Header

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

@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}

@end

MainFile

In the init method

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[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);
}

iOS 6

In iOS 6 the delegate function was deprecated. The new delegate is

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

Therefore to get the new position use

[locations lastObject]

iOS 8

In iOS 8 the permission should be explicitly asked before starting to update location

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];

You also have to add a string for the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys to the app's Info.plist. Otherwise calls to startUpdatingLocation will be ignored and your delegate will not receive any callback.

And at the end when you are done reading location call stopUpdating location at suitable place.

[locationManager stopUpdatingLocation];

SwiftUI: How to get the current location of user?

Yes, it's been deprecated in favour of using a property of the same name instead of a function, try it without the parentheses...

if manager.authorizationStatus == .authorizedWhenInUse {

Get current location on iOS

From iOS 10 you need to add two keys to the info.plist as

NSLocationAlwaysUsageDescription key to your Info.plist file. (Xcode displays this key as "Privacy - Location Always Usage Description" in the Info.plist editor.)

And for iOS 11

Add the NSLocationWhenInUseUsageDescription key and the NSLocationAlwaysAndWhenInUseUsageDescription key to your Info.plist file. (Xcode displays these keys as "Privacy - Location When In Use Usage Description" and "Privacy - Location Always and When In Use Usage Description" in the Info.plist editor.)

Also find the complete guide at apple documentation at: apple corelocation authorization

How to get current location IOS device

I give you the solution step by step

STEP 1:

First we should get the
Google Map SDK

Drag the following bundles into your project (when prompted, select Copy items if needed):

Subspecs/Base/Frameworks/GoogleMapsBase.framework
Subspecs/Maps/Frameworks/GoogleMaps.framework
Subspecs/Maps/Frameworks/GoogleMapsCore.framework

Right-click GoogleMaps.framework in your project, and select Show In Finder.

Drag the GoogleMaps.bundle from the Resources folder into your project. When prompted, ensure Copy items into destination group's folder is not selected.

Select your project from the Project Navigator, and choose your application's target.

Open the Build Phases tab, and within Link Binary with Libraries, add the following frameworks:

GoogleMapsBase.framework
GoogleMaps.framework
GoogleMapsCore.framework
GoogleMapsM4B.framework (Premium Plan customers only)
Accelerate.framework
CoreData.framework
CoreGraphics.framework
CoreLocation.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.tbd
libz.tbd
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework
UIKit.framework

STEP 2:

Get the API key

STEP 3:

Add the below things in your Plist    

App Transport Security Settings Dictionary
Allow Arbitrary Loads Boolean YES


<key>NSLocationWhenInUseUsageDescription</key>
<string>RehabTask requires location services to work</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>RehabTask requires location services to work</string>

OR

Privacy - Location When In Use Usage Description string RehabTask requires location services to work
Privacy - Location Always Usage Description string RehabTask requires location services to work

Also you need to add

  <key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>

STEP 4: In appDelegate add below code

AppDelegate.m

@import GoogleMaps;
#import "AppDelegate.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[GMSServices provideAPIKey:@"AIzaSyCrCEb7qVkURIjq6jsfkPkwgN62sfj6Ff0"];
return YES;
}

STEP 5:

ViewController.h

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


@interface ViewController : UIViewController<CLLocationManagerDelegate,GMSMapViewDelegate>{
CLLocation *currentLocation;
}

@property (strong, nonatomic) IBOutlet UIView *viewDirection;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) GMSMapView *mapView;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize viewDirection,locationManager,
@synthesize mapView;

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.distanceFilter = 10;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([CLLocationManager locationServicesEnabled] == NO){
NSLog(@"Your location service is not enabled, So go to Settings > Location Services");
}
else{
NSLog(@"Your location service is enabled");
}
if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
currentLocation = [locations lastObject];
if (currentLocation != nil){
NSLog(@"The latitude value is - %@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
NSLog(@"The logitude value is - %@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);
}
//Current
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:currentLocation.coordinate.latitude longitude: currentLocation.coordinate.longitude zoom:13];

self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.mapView.myLocationEnabled = YES;
self.mapView.delegate = self;
self.mapView.frame = viewDirection.bounds;
[viewDirection addSubview:self.mapView];

GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
marker.title = @"Your Office Name";
marker.icon = [UIImage imageNamed:@"boss-icon.png"];
OR
marker.icon = [GMSMarker markerImageWithColor:[UIColor blueColor]];
marker.snippet = @"Current Location";
marker.map = self.mapView;


GMSMarker *marker1 = [[GMSMarker alloc] init];
marker1.position = CLLocationCoordinate2DMake(22.7007,75.8759);
marker1.icon = [GMSMarker markerImageWithColor:[UIColor redColor]];
marker1.title = @"Place Name";
marker1.snippet = @"City Name";
marker1.map = self.mapView;


GMSMarker *marker2 = [[GMSMarker alloc] init];
marker2.position = CLLocationCoordinate2DMake(22.6990,75.8671);
marker2.icon = [GMSMarker markerImageWithColor:[UIColor greenColor]];
marker2.title = @"Place Name";
marker2.snippet = @"City Name";
marker2.map = self.mapView;

NSString *originString = [NSString stringWithFormat:@"%f,%f",22.7007,75.8759];

NSString *destinationString = [NSString stringWithFormat:@"%f,%f",22.6990,75.8671];

NSString *str = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false",originString,destinationString];
NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data == nil) {
return;
}else{
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* latestRoutes = [json objectForKey:@"routes"];
NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
@try {
// TODO: better parsing. Regular expression?
NSArray *temp= [self decodePolyLine:[points mutableCopy]];
GMSMutablePath *path = [GMSMutablePath path];
for(int idx = 0; idx < [temp count]; idx++){
CLLocation *location=[temp objectAtIndex:idx];
[path addCoordinate:location.coordinate];
}
// create the polyline based on the array of points.
GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
rectangle.strokeWidth=5.0;
rectangle.map = self.mapView;
[locationManager stopUpdatingLocation];
}
@catch (NSException * e) {
// TODO: show erro
}
}
}];
[dataTask resume];
}
[locationManager stopUpdatingLocation];
}

//I called below method in above temp(NSArray *temp = [self decodePolyLine:[points mutableCopy]]) for Drawing route between two or more places
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init] ;
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5] ;
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5] ;
printf("[%f,", [latitude doubleValue]);
printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;
[array addObject:loc];
}

return array;
}

@end

Happy Coding :-)

Not getting users current location in swift 4

The problem is your Info.plist. You need all three keys:

Sample Image

Fix that and the app will spring to life. I pasted your code into a project, set up the Info.plist as shown, and it worked fine.

You can actually omit "Always" starting in iOS 11, but you must have both "When In Use" and "Always and When In Use", even if you are planning to ask only for "Always".

The runtime was in fact telling you this all along in the Xcode console, but you apparently weren't looking at it. It says:

The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data.

Get User Current location using CLLocation in IOS

Check My code you can get address from current location

- (void)viewDidLoad {
CLGeocoder *ceo;

self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[locationManager startUpdatingLocation];
}



-(void)viewDidAppear:(BOOL)animated{
ceo= [[CLGeocoder alloc]init];
[self.locationManager requestWhenInUseAuthorization];
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
CLLocationCoordinate2D coordinate;

coordinate.latitude=locationManager.location.coordinate.latitude;
coordinate.longitude=locationManager.location.coordinate.longitude;
//CLLocationCoordinate2D ctrpoint;
// ctrpoint.latitude = ;
//ctrpoint.longitude =f1;
//coordinate.latitude=23.6999;
//coordinate.longitude=75.000;
MKPointAnnotation *marker = [MKPointAnnotation new];
marker.coordinate = coordinate;
NSLog(@"%f",coordinate.latitude);
//[self.mapView addAnnotation:marker];


CLLocation *loc = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude
];
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark %@",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSLog(@"addressDictionary %@", placemark.addressDictionary);

NSLog(@"placemark %@",placemark.region);
NSLog(@"placemark %@",placemark.country); // Give Country Name
NSLog(@"placemark %@",placemark.locality); // Extract the city name
NSLog(@"location %@",placemark.name);
NSLog(@"location %@",placemark.ocean);
NSLog(@"location %@",placemark.postalCode);
NSLog(@"location %@",placemark.subLocality);

NSLog(@"location %@",placemark.location);
//Print the location to console
NSLog(@"I am currently at %@",locatedAt);


_City.text=[placemark.addressDictionary objectForKey:@"City"];
[locationManager stopUpdatingLocation];
}

];
}





#pragma mark - CLLocationManagerDelegate

Please add this two method

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

Hope This work

Thank you

how to get user current location in simulator in iphone sdk?

On iOS5 Simulator by default you it will show some location in USA. If you want to change that location, in iOS Simulator menu, go to Debug -> Location -> Custom Location.
There you can set the latitude and longitude and test the app accordingly. This works with mapkit and also with CLLocationManager.



Related Topics



Leave a reply



Submit