사용자의 현재 도시 이름을 검색하는 방법은?
사용자의 현재 도시 이름을 어떻게 검색합니까?
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";
당신이 해야 할 일은 당신이 준비하는 것입니다.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);
}
이 방법은 저에게 효과가 있습니다.
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);
}];
MKRverseGeocoder에서 CLGeocoder로 이동하려는 사람이 있다면, 저는 도움이 될 수 있는 블로그 게시물을 작성했습니다. http://jonathanfield.me/jons-blog/clgeocoder-example.html
기본적으로 locationManager 및 CLGeocoder 개체를 만든 후 이 코드를 보기 DidLoad()에 추가한 다음 데이터를 표시하기 위해 일부 레이블이나 텍스트 영역을 만듭니다.
[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;
}];
CLLocation Manager를 설정하면 위도/경도 쌍으로 위치가 업데이트됩니다.그런 다음 CLGeocoder를 사용하여 좌표를 사용자에게 친숙한 플레이스 이름으로 변환할 수 있습니다.
스위프트 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()
}
}
}
}
}
스위프트 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!)"
}
}
}
사용자의 현재 위치를 파악한 후 MKRverseGeocoder를 사용하여 도시를 인식해야 합니다.
아이폰 앱 프로그래밍 가이드 8장에 좋은 예가 있습니다.위치 초기화 지오코더가 있으면 위임자를 설정하고 장소 표시에서 국가를 읽습니다.MKRverseGeocodeDelegate 설명서를 읽고 메소드를 만듭니다.
- reverseGeocoder: DidFindPlacemark:
reverseGeocoder:didFailWithError:
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; geocoder.delegate = self; [geocoder start];
이 코드를 사용하여 Current City를 가져올 수 있습니다.--
컨트롤러 확장: CLLocationManager위임 {funcocationManager위임 {funcocationManager위임(관리자: CLLocationManager위임, 위치 업데이트 실행: [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
}
}
여기 현재 위치에 대한 역 지오코딩 정보를 얻는 데 도움이 되는 작은 스위프트 클래스가 있습니다.잊지마세요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);
}];
}
MKRverseGeocoder용 설명서를 읽어 보십시오. 설명서, 가이드 및 샘플 애플리케이션은 이유가 있습니다.
언급URL : https://stackoverflow.com/questions/1382900/how-to-retrieve-users-current-city-name
'programing' 카테고리의 다른 글
| SQLPLUS를 통한 Oracle 데이터베이스 연결 (0) | 2023.10.10 |
|---|---|
| 타이프스크립트에서 npm 모듈을 소비하는 방법은? (0) | 2023.10.10 |
| 도커의 공정에서 탈부착은 어떻게 합니까? (0) | 2023.10.10 |
| 단일 배열 매개 변수를 사용하는 생성자에 대해 New-Object를 호출하려면 어떻게 해야 합니까? (0) | 2023.10.10 |
| Angular.js 프레임워크의 추가 js 파일은 무엇을 위한 것입니까? (0) | 2023.10.10 |