私はこのようなプロジェクトをやっています。Swift:マップビューが消えた/再表示された後にMapView geocodeAddressStringが機能しない
は郵便番号を取得し、地図上のジップコード領域を示す地図ビュー・コントローラにセグエに郵便番号を渡し、テキストボックス/ボタンを持っています。セットアップ全体がナビゲーションコントローラの背後にあるので、前のビューで別の郵便番号を試してみることができます。
問題は、地図ビューが初めて郵便番号を適切にプロットするが、前のビューコントローラで別の郵便番号を入力したときに、地図ビューでその地域が新しいジップに設定されないということですコードを正しく作成する代わりに、シミュレータ内のデフォルト領域を含む新しいマップビューを表示します。私は戻って、ナビゲーションコントローラの最初のビューに戻り、他の郵便番号を打ったときに問題がある以下のコード
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView!
var searchZipCode:String! = "95110" //used by other segues to set zipcode to show on this page
let locationManager = CLLocationManager()
let geocoder = CLGeocoder()
var dispatchGroup = dispatch_group_create()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
dispatchGroup = dispatch_group_create()
dispatch_group_enter(dispatchGroup)
self.plotZipCodeInMap(self.searchZipCode)
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()){
print("Zip code plotted.")
}
func plotZipCodeInMap(zipCode:String) {
geocoder.geocodeAddressString(zipCode, completionHandler: {(placemarks, error) -> Void in
print("Zip code = \(zipCode)")
if let placemark = placemarks?.first {
print("Successfully decoded the zip code..")
let coordinate = placemark.location?.coordinate
let center = CLLocationCoordinate2D(latitude: coordinate!.latitude, longitude: coordinate!.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.04, longitudeDelta: 0.04))
self.mapView.setRegion(region, animated: true)
dispatch_group_leave(self.dispatchGroup)
}
})
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Location updated..")
let locations = locations.last
let center = CLLocationCoordinate2D(latitude: locations!.coordinate.latitude, longitude: locations!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.075, longitudeDelta: 0.075))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
}
を参照してください、マップビューが正しくplotZipCodeInMap方法を入力しているようだが、それは行を印刷しない
は「成功しました郵便番号をデコード..」
を目印をもう一度得ることにいくつかの問題があることを意味しています。ここで何が問題になるのかはわかりません。変数はすべてローカルであり、戻るボタンをクリックすると(マップビューが消える)、ビューが別の郵便番号で表示されます。