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);
}
} ];
Get Three Letter Country Code From Two Letter Country Code