IOS gets the current city
1. Import the header file
# Import
2. Implement the location protocol CLLocationManagerDelegate
3. Define positioning attributes
@ Property (nonatomic, retain) CLLocationManager * locationManager;
4. Start locating
-(Void) locate
{
// Determine whether the positioning operation is permitted
If ([CLLocationManagerlocationServicesEnabled]) {
Self. locationManager = [[CLLocationManageralloc] init];
Self. locationManager. delegate = self;
} Else {
// Prompt that the user cannot locate
UIAlertView * alertView = [[UIAlertViewalloc] initWithTitle:
@ "Prompt" message: @ "positioning failed. Please confirm to enable positioning" delegate: nilcancelButtonTitle: @ "cancel" otherButtonTitles: @ "OK", nil];
[AlertViewshow];
}
// Start locating
[Self. locationManagerstartUpdatingLocation];
}
5. Implement the locating protocol callback Method
# Pragma mark-CoreLocation Delegate
-(Void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray *) locations
{
// Here, locations stores the position coordinate value of continuous update, and obtains the last value as the latest position. If you do not want it to be updated continuously, after obtaining a value in this method, let locationManager stopUpdatingLocation
CLLocation * currentLocation = [locations lastObject];
// Obtain the name of the current city
CLGeocoder * geocoder = [[CLGeocoderalloc] init];
// Returns the address information based on the latitude and longitude.
[GeocoderreverseGeocodeLocation: currentLocation completionHandler: ^ (NSArray * array, NSError * error)
{
If (array. count> 0)
{
CLPlacemark * placemark = [array objectAtIndex: 0];
// Display all obtained information on the label
NSLog (@ "% @", placemark. name );
// Obtain the city
NSString * city = placemark. locality;
If (! City ){
// The city information of the four municipalities cannot be obtained through locality, but can only be obtained by obtaining the province information (if the city is empty, it can be known as a municipality)
City = placemark. administrativeArea;
}
Self. cityName = city;
}
Else if (error = nil & [array count] = 0)
{
NSLog (@ "No results were returned .");
}
Else if (error! = Nil)
{
NSLog (@ "An error occurred = % @", error );
}
}];
// The system will update the data until you choose to stop the update. Because we only need to obtain the longitude and latitude once, the update will be stopped after obtaining the data.
[Manager stopUpdatingLocation];
}
-(Void) locationManager :( CLLocationManager *) manager
DidFailWithError :( NSError *) error {
If (error. code = kCLErrorDenied ){
// Indicates the cause of the error. You can press and hold the Option key and click KCLErrorDenied to view more error information. You can print the error. code value to find the cause.
}
}