How to Get Current Location Using Cllocationmanager 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];

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

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 current longitude and latitude using CLLocationManager-Swift

IMHO, you are over complicating your code when the solution you are looking is pretty simple.

I have done it by using the following code:

First create an instance of CLLocationManager and Request Authorization

var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()

then check if the user allowed authorization.

var currentLocation: CLLocation!

if
CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways
{
currentLocation = locManager.location
}

to use it just do this

label1.text = "\(currentLocation.coordinate.longitude)"
label2.text = "\(currentLocation.coordinate.latitude)"

Your idea of setting them to the label.text is correct, however the only reason I can think of is that the user is not giving you permission and that is why your current Location data will be nil.

However you would need to debug and tell us that.
Also the CLLocationManagerDelegate is not necessary.

Hopefully this helps. Ask away if you have doubts.

How to get Current Location using SwiftUI, without ViewControllers?

You could create a StateObject of your LocationManager by implementing the ObservableObject protocol.

With the @Published attribute you can create a publisher object which notify the observers (your view, in this case) when something changes inside that object.

That's why in my LocationManager I added the @Published attribute to those var:

  1. locationStatus: CLAuthorizationStatus? it contains the value received from didChangeAuthorization delegate method
  2. lastLocation: CLLocation? it contains the last location calculated by the didUpdateLocations delegate method

LocationManager

import Foundation
import CoreLocation
import Combine

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {

private let locationManager = CLLocationManager()
@Published var locationStatus: CLAuthorizationStatus?
@Published var lastLocation: CLLocation?

override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}



var statusString: String {
guard let status = locationStatus else {
return "unknown"
}

switch status {
case .notDetermined: return "notDetermined"
case .authorizedWhenInUse: return "authorizedWhenInUse"
case .authorizedAlways: return "authorizedAlways"
case .restricted: return "restricted"
case .denied: return "denied"
default: return "unknown"
}
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
locationStatus = status
print(#function, statusString)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
lastLocation = location
print(#function, location)
}
}

View

In your view you need to create only an instance of LocationManager marked as @StateObject

import SwiftUI

struct MyView: View {

@StateObject var locationManager = LocationManager()

var userLatitude: String {
return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
}

var userLongitude: String {
return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
}

var body: some View {
VStack {
Text("location status: \(locationManager.statusString)")
HStack {
Text("latitude: \(userLatitude)")
Text("longitude: \(userLongitude)")
}
}
}
}

struct MyView_Previews: PreviewProvider {
static var previews: some View {
MyView()
}
}

Sample Image

How to get current location in ios in simulator?

Create a GPX file by using following steps:

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

Sample Image

  • 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

    Sample Image

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

Sample Image

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

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 :-)



Related Topics



Leave a reply



Submit