2017-10-22 10 views
3

CLLocationDegreesを入力し、CLPlacemarkを返す簡単なメソッドを作成しようとしています。 Apple's documentationを見ると、簡単な作業のようです。以下はSwiftの逆ジオコーディング4

は、私が遊び場に捨ててきたものである:

import CoreLocation 
// this is necessary for async code in a playground 
import PlaygroundSupport 

// this is necessary for async code in a playground 
PlaygroundPage.current.needsIndefiniteExecution = true 

func geocode(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> CLPlacemark? { 
    let location = CLLocation(latitude: latitude, longitude: longitude) 
    let geocoder = CLGeocoder() 

    var placemark: CLPlacemark? 

    geocoder.reverseGeocodeLocation(location) { (placemarks, error) in 
    if error != nil { 
     print("something went horribly wrong") 
    } 

    if let placemarks = placemarks { 
     placemark = placemarks.first 
    } 
    } 

    return placemark 
} 

let myPlacemark = geocode(latitude: 37.3318, longitude: 122.0312) 

現状では

、私の方法はnilを返しています。私のエラーがどこにあるのかは分かりませんが、私はそれが何かに驚くほど愚かなことを確信しています。読んでくれてありがとう。

+3

geocoder.reverseGeocodeLocationは非同期です。完了ハンドラが必要です –

+0

ありがとうございます。私はそれを理解することができるかどうかがわかります。 – Adrian

+0

私の投稿が間違っていた。私の編集をチェックしてください。あなたのコードを貼り付けてコピーし、2倍の代わりに2つの場所を渡していたことに気付かなかった –

答えて

4
import UIKit 
import CoreLocation 
import PlaygroundSupport 
PlaygroundPage.current.needsIndefiniteExecution = true 

func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) ->()) { 
    CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { placemarks, error in 
     guard let placemark = placemarks?.first, error == nil else { 
      completion(nil, error) 
      return 
     } 
     completion(placemark, nil) 
    } 
} 

使用法:目印のプロパティの詳細については

geocode(latitude: -22.963451, longitude: -43.198242) { placemark, error in 
    guard let placemark = placemark, error == nil else { return } 
    // you should always update your UI in the main thread 
    DispatchQueue.main.async { 
     // update UI here 
     print("address1:", placemark.thoroughfare ?? "") 
     print("address2:", placemark.subThoroughfare ?? "") 
     print("city:",  placemark.locality ?? "") 
     print("state:", placemark.administrativeArea ?? "") 
     print("zip code:", placemark.postalCode ?? "") 
     print("country:", placemark.country ?? "")  
    } 
} 

あなたはこれが

を出力します。この CLPlacemark


を確認することができます

address1: Rua Casuarina 
address2: 443 
city: Rio de Janeiro 
state: RJ 
zip code: 20975 
country: Brazil 
+0

ありがとうございました!これは仕事を終わらせる。私は非同期コードであるため、このような 'let'定数を宣言できるとは思えません。私はこれを '' myPlacemark = geocode(緯度:37.3318、経度:122.0312) 'と別のものでリファクタリングします。 – Adrian

+0

クロージャ内で使用する必要があります –

+0

パーフェクト。ありがとうございました! – Adrian

関連する問題