사용자의 현재 도시 이름을 어떻게 검색합니까?
답변
해야 할 일은 CLLocationManager
현재 좌표를 찾을 수 있도록 설정하는 것입니다. 현재 좌표를 사용 MKReverseGeoCoder
하여 위치를 찾는 데 사용해야 합니다.
- (void)viewDidLoad
{
// this creates the CCLocationManager that will find your current location
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
// this delegate is called when the app successfully finds your current location
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// this creates a MKReverseGeocoder to find a placemark using the found coordinates
MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geoCoder.delegate = self;
[geoCoder start];
}
// this delegate method is called if an error occurs in locating your current location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"locationManager:%@ didFailWithError:%@", manager, error);
}
// this delegate is called when the reverseGeocoder finds a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
MKPlacemark * myPlacemark = placemark;
// with the placemark you can now retrieve the city name
NSString *city = [myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];
}
// this delegate is called when the reversegeocoder fails to find a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);
}
답변
iOS 5 MKReverseGeoCoder
부터는 더 이상 사용되지 않습니다!
그래서 당신은 , 매우 간단하고 블록과 CLGeocoder
함께 사용하고 싶습니다 CLLocationManager
.
예:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[self.locationManager stopUpdatingLocation];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
.... = [placemark locality];
}
}];
}
편집 :for in
루프 대신 다음을 수행 할 수도 있습니다.
NSString *locString = placemarks.count ? [placemarks.firstObject locality] : @"Not Found";
답변
이것은 나를 위해 잘 작동합니다.
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:self.locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode);
NSLog(@"placemark.country %@",placemark.country);
NSLog(@"placemark.postalCode %@",placemark.postalCode);
NSLog(@"placemark.administrativeArea %@",placemark.administrativeArea);
NSLog(@"placemark.locality %@",placemark.locality);
NSLog(@"placemark.subLocality %@",placemark.subLocality);
NSLog(@"placemark.subThoroughfare %@",placemark.subThoroughfare);
}];
답변
누군가 MKReverseGeocoder에서 CLGeocoder로 이동하려는 경우 도움이 될 수있는 블로그 게시물을 작성했습니다. http://jonathanfield.me/jons-blog/clgeocoder-example.html
기본적으로 예제는 locationManager 및 CLGeocoder 객체를 만든 후이 코드를 viewDidLoad ()에 추가 한 다음 데이터를 표시 할 레이블 또는 텍스트 영역을 만드는 것입니다.
[super viewDidLoad];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[self.CLGeocoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
isoCountryCode.text = placemark.ISOcountryCode;
country.text = placemark.country;
postalCode.text= placemark.postalCode;
adminArea.text=placemark.administrativeArea;
subAdminArea.text=placemark.subAdministrativeArea;
locality.text=placemark.locality;
subLocality.text=placemark.subLocality;
thoroughfare.text=placemark.thoroughfare;
subThoroughfare.text=placemark.subThoroughfare;
//region.text=placemark.region;
}];
답변
CLLocationManager를 설정 한 후 위도 / 경도 쌍으로 위치 업데이트를 받게됩니다. 그런 다음 CLGeocoder를 사용하여 좌표를 사용자에게 친숙한 장소 이름으로 변환 할 수 있습니다.
다음은 Swift 4 의 샘플 코드입니다 .
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lastLocation = locations.last {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(lastLocation) { [weak self] (placemarks, error) in
if error == nil {
if let firstLocation = placemarks?[0],
let cityName = firstLocation.locality { // get the city name
self?.locationManager.stopUpdatingLocation()
}
}
}
}
}
답변
누구든지 Swift 3 에서 필요한 경우 다음 과 같이했습니다.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
self.location = location
self.locationManager?.stopUpdatingLocation()
// Drop a pin at user's Current Location
let myAnnotation: MKPointAnnotation = CustomPointAnnotation()
myAnnotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
myAnnotation.title = "Localização"
self.mapViewMK.addAnnotation(myAnnotation)
self.mapViewMK.setRegion(coordinateRegion, animated: true)
self.locationManager?.stopUpdatingLocation()
self.locationManager = nil
// Get user's current location name
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(self.location!) { (placemarksArray, error) in
if (placemarksArray?.count)! > 0 {
let placemark = placemarksArray?.first
let number = placemark!.subThoroughfare
let bairro = placemark!.subLocality
let street = placemark!.thoroughfare
self.addressLabel.text = "\(street!), \(number!) - \(bairro!)"
}
}
}
답변
사용자의 현재 위치를 확인한 다음 MKReverseGeocoder를 사용하여 도시를 인식해야합니다.
iPhone App Programming Guide , 8 장 에 좋은 예가 있습니다. 위치 초기화 지오 코더가 있으면 대리자를 설정하고 장소 표시에서 국가를 읽습니다. MKReverseGeocodeDelegate에 대한 설명서를 읽고 메서드를 만듭니다.
- reverseGeocoder : didFindPlacemark :
-
reverseGeocoder : didFailWithError :
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; geocoder.delegate = self; [geocoder start];