1. Pour the header file
#import <CoreLocation/CoreLocation.h>
2. Implement the positioning protocol cllocationmanagerdelegate
3. Defining positioning Properties
@property(nonatomic,retain)cllocationmanager *locationmanager;
4. Start positioning
-(void) Locate
{
// determine if the location operation is allowed
if([cllocationmanagerlocationservicesenabled]) {
Self. Locationmanager = [[cllocationmanageralloc] init];
self. Locationmanager . Delegate = Self ;
}Else {
// Prompt the user for no location operation
uialertview *alertview = [[uialertviewalloc]initwithtitle:
@"Tips"Message:@"Location not successful ,make sure to turn on positioning"Delegate:NilCancelbuttontitle:@"Cancel"Otherbuttontitles:@"Determine",Nil];
[Alertviewshow];
}
// start positioning
[self. Locationmanager startupdatinglocation];
}
5. Implement the positioning protocol callback method
#pragma mark-corelocation Delegate
-(void) Locationmanager: (cllocationmanager *) Manager didupdatelocations: (nsarray *) Locations
{
/// here Locations stores the constant updated location coordinate value, takes the last value to the latest position, and if you do not want it to keep updating the location, then get a value in this method Locationmanager stopupdatinglocation
cllocation *currentlocation = [Locations lastobject];
// Get the name of your current city
clgeocoder *geocoder = [[clgeocoderalloc] init];
// Reverse geo-compilation of address information based on latitude and longitude
[Geocoderreversegeocodelocation: currentlocation completionhandler: ^ (nsarray *array, nserror *error)
{
if (Array. count >0)
{
clplacemark *placemark = [array objectatindex:0];
// to display all information obtained on the label
NSLog (@ "%@", Placemark. name);
// get the city
nsstring *city = placemark. locality;
if (!city) {
// The city information of the four municipalities cannot be obtained by locality , but only by obtaining the province's method (if it is empty, it is known as the 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 keep updating the data until you choose to stop the update, because we just need to get a latitude and longitude, so get it and stop the update
[manager stopupdatinglocation];
}
-(void) Locationmanager: (cllocationmanager *) Manager
Didfailwitherror: (nserror *) Error {
if (Error.) code = =kclerrordenied) {
// Prompt the user for error reasons, you can press the Option key to view more error messages, print Error.code value to find the cause of the kclerrordenied
}
}
iOS get current city