사용자의 현재 도시 이름을 어떻게 검색합니까?
답변:
해야 할 일은 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);
}];
kCLErrorDomain error 8
가 발생 합니다. 이유를 알고 있습니까?
누군가 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;
}];
nil
, 및을 (를) 통해 점 표기법을 통한 속성 액세스뿐 아니라 nil
결과로 전송 된 메시지 nil
도 포함됩니다 nil
. 그 존재는 하나가 항상 여부를 확인해야했다 error
비입니다 nil
.
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 : didFailWithError :
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geocoder.delegate = self;
[geocoder start];
이 코드를 사용하여 현재 도시를 가져올 수 있습니다.
extension YourController : CLLocationManagerDelegate {func locationManager (manager : CLLocationManager, didUpdateLocations 위치 : [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil)
{
manager.stopUpdatingLocation()
return
}
else
{
if placemarks!.count > 0
{
let placeMarksArrray: NSArray = placemarks!
let pm = placeMarksArrray[0] as! CLPlacemark
self.displayLocationInfo(pm)
manager.stopUpdatingLocation()
} else
{
print("Problem with the data received from geocoder")
}
}
})
}
func displayLocationInfo(placemark: CLPlacemark!) {
if (placemark != nil) {
//stop updating location to save battery life
locationLocation.stopUpdatingLocation()
var tempString : String = ""
if(placemark.locality != nil){
tempString = tempString + placemark.locality! + " "
print(placemark.locality)
}
if(placemark.postalCode != nil){
tempString = tempString + placemark.postalCode! + " "
print(placemark.postalCode)
}
if(placemark.administrativeArea != nil){
tempString = tempString + placemark.administrativeArea! + " "
print(placemark.administrativeArea)
}
if(placemark.country != nil){
tempString = tempString + placemark.country! + " "
}
let dictForaddress = placemark.addressDictionary as! NSDictionary
if let city = dictForaddress["City"] {
print(city)
}
strLocation = tempString
}
}
다음은 현재 위치에 대한 역 지오 코딩 된 정보를 얻는 데 도움이되는 작은 Swift 클래스입니다. .NET의 NSLocationWhenInUseUsageDescription
필드를 잊지 마세요 Info.plist
.
class CurrentPlacemarkUpdater: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private let geocoder = CLGeocoder()
private(set) var latestPlacemark: CLPlacemark?
var onLatestPlacemarkUpdate: (() -> ())?
var shouldStopOnUpdate: Bool = true
func start() {
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func stop() {
locationManager.stopUpdatingLocation()
}
fileprivate func updatePlacemark(for location: CLLocation) {
geocoder.reverseGeocodeLocation(location) { [weak self] placemarks, error in
if let placemark = placemarks?.first {
self?.latestPlacemark = placemark
self?.onLatestPlacemarkUpdate?()
if self?.shouldStopOnUpdate ?? false {
self?.stop()
}
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
updatePlacemark(for: location)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("CurrentPlacemarkUpdater: \(error)")
}
}
// place the function code below in desire location in program.
// [self getCurrentLocation];
-(void)getCurrentLocation
{
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.locality %@",placemark.locality );
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에 대한 문서를 읽으십시오. 문서 , 가이드 및 샘플 응용 프로그램은 이유 때문에 Apple에서 제공합니다.