Skip to content

Instantly share code, notes, and snippets.

@JeOam
Last active January 4, 2022 07:57
Show Gist options
  • Save JeOam/72432e191ee4adccbc55 to your computer and use it in GitHub Desktop.
Save JeOam/72432e191ee4adccbc55 to your computer and use it in GitHub Desktop.
Get Current Location in iOS

You use the CoreLocation framework to access location information about your user. You will need to instantiate a CLLocationManager object and call the asynchronous startUpdatingLocation message. You will get callbacks with the user's location via the CLLocationManagerDelegate that you supply.


NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.iOS Simulator -> Debug -> Location

Step 1: Import CoreLocation framework

#import <CoreLocation/CoreLocation.h>

Step 2: Add delegate CLLocationManagerDelegate

@interface ViewController ()<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
    
    CLGeocoder *geocoder;
    CLPlacemark *placemark;
}
@end

Step 3: Add this code in class file

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation]; // 这里会提示用户获取地理位置的权限
    [locationManager performSelector:@selector(stopUpdatingLocation) withObject:nil afterDelay:60]; // 60 秒后停止监听
}

Step 4: Get location using this method

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations lastObject];
    [locationManager stopUpdatingLocation];
    NSLog(@"currentLocation is %@",currentLocation);
}

Step 5: Converting GPS Coordinate into User-readable Address By specify the latitude and longitude of a given location, you can use CLGeocoder to find a user-readable address. The result (i.e. the address) returned by CLGeocoder is saved in a CLPlacemark object.

geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
    if (error == nil && [placemarks count] > 0) {
        placemark = [placemarks lastObject];
        NSString *countryCode = placemark.ISOcountryCode;
        if (countryCode.length == 2) {
            countryCode = [self GetThreeLetterCountryCodeFromTwoLetterCountryCode:countryCode]
            NSLog(@"countryCode is %@", countryCode);
            [locationManager stopUpdatingLocation];
        }
        // 获取想要的信息后停止监听
        [locationManager stopUpdatingLocation];
    } else {
        NSLog(@"%@", error.debugDescription);
    }
} ];

Ref: How can I get current location from user in iOS

@JeOam
Copy link
Author

JeOam commented Jul 22, 2014

@JeOam
Copy link
Author

JeOam commented Jul 22, 2014

定位出错提示:

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

@JeOam
Copy link
Author

JeOam commented Jul 22, 2014

Get ISOCurrencyCode from a ISOCountryCode:

NSString *countryCode = @"US";

NSDictionary *components = [NSDictionary dictionaryWithObject:countryCode forKey:NSLocaleCountryCode];
NSString *localeIdent = [NSLocale localeIdentifierFromComponents:components]; 
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeIdent] autorelease];
NSString *currencyCode = [locale objectForKey: NSLocaleCurrencyCode];

via here

@JeOam
Copy link
Author

JeOam commented Sep 28, 2014

获取广东省广州市字样的位置:

CLPlacemark *placemark = [placemarks firstObject];
NSString *text = [NSString stringWithFormat:@"%@%@", placemark.administrativeArea, placemark.locality];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment