IOS-use CoreLocation to get the current city
In the previous blog-CoreLocation-iOS location information, we briefly described the use of CoreLocation and obtained latitude and longitude information. next, we will reverse parse the current city and other information from the geographic location information.
First, initialize the CLLocationManager object and set delegate,
Then, startUpdatingLocation begins to be located.
Note: The CLLocationManagerDelegate protocol must be inherited.
@ Property (strong, nonatomic) CLLocationManager * locationManager; # pragma mark-get the current location city-(void) locate {self. currentCity = [[NSString alloc] init]; // determines whether to enable the if ([CLLocationManager locationServicesEnabled]) {self. locationManager = [[CLLocationManager alloc] init]; self. locationManager. delegate = self; [self. locationManager startUpdatingLocation];} else {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString (@ resolve, comment: @ cannot locate) message: NSLocalizedString (@ resolve, comment: @ check whether positioning is enabled on your device) delegate: self cancelButtonTitle: NSLocalizedString (@ common_confirm, comment: @ OK) otherButtonTitles: nil, nil]; [alert show];}
Then, the didUpdateLocations method is implemented and the city information is parsed.
# Pragma mark-CoreLocation Delegate-(void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray *) locations {CLLocation * currentLocation = [locations lastObject]; // The last value is the latest location CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; // obtain the location and city information in reverse direction based on the longitude and latitude [geoCoder reverseGeocodeLocation: currentLocation completionHandler: ^ (NSArray * placemarks, NSError * error) {if (placemarks. count> 0) {CLPlacemark * placeMark = placemarks [0]; self. currentCity = placeMark. locality ;//? PlaceMark. locality: placeMark. administrativeArea; if (! Self. currentCity) {self. currentCity = NSLocalizedString (@ home_cannot_locate_city, comment: @ unable to locate the current city);} // after obtaining the city information, asynchronously update the interface information. dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {dispatch_async (dispatch_get_main_queue (), ^ {self. cityDict [@ *] = @ [self. currentCity]; [self. tableView reloadSections: [NSIndexSet indexSetWithIndex: 0] withRowAnimation: UITableViewRowAnimationNone] ;});} else if (error = nil & placemarks. count = 0) {NSLog (@ No location and error returned);} else if (error) {NSLog (@ Location error: % @, error) ;}}]; [manager stopUpdatingLocation];}
Result:
Unable to locate |
Positioning successful |
|
|