緯度と経度を持ちながら都市の名前を取得しようとしています。 モデルクラスLocation
では、CLGeocoder(CoreLocationの一部)に付属のreverseGeocodeLocation(location: , completionHandler:)
funcを使用しています。終了ハンドラは非同期で、まだ終わっていなかったので、非同期完了ハンドラからデータを取得
func getLocationName() {
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
})
}
しかし、ViewController
で、getLocationName()
を実行した後、location.currentCity
は、nil
です。
location.currentCity
にアクセスできるように、完了ハンドラが実行されていることを確認するにはどうすればよいですか?
だけでアクセス 'location.currentCity' **で**完了ハンドラまたは非同期にデータを返すために、')( 'getLocationNameに別の完了ハンドラを追加。 – vadian
「完了ハンドラが実行を終了していることを確認してください」というのではなく、 'completionHandler'の' location.currentCity'で何をしたいのですか? –
@vadian私は 'location.currentCity'にアクセスする必要があります。コントローラ、(Locationクラスの外)UIを更新しました。別の補完ハンドラを追加してモデルクラス内のUIを更新しない方が良いでしょうか? 新しい補完ハンドラをどのように実装する必要があるかのサンプルコードを提供できますか? –