2017-10-22 74 views
3

我試圖寫一個簡單的方法,餵了CLLocationDegrees並返回CLPlacemark。看着Apple's documentation,這看起來很簡單。反向地理編碼在斯威夫特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

我的帖子是錯誤的。檢查我的編輯。我複製粘貼你的代碼,並沒有注意到你通過兩個位置,而不是兩個雙打 –

回答

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'常量。我會用別的東西來重構這個'let myPlacemark = geocode(latitude:37.3318,longitude:122.0312) '。 – Adrian

+0

您需要在封閉內使用它 –

+0

完美。謝謝! – Adrian