2012-11-24 137 views
2

在我的應用程序中,我需要知道用戶所在街道的名稱。此刻,我只知道用戶可以通過CLLocationManger對象獲取用戶位置,並在MKMapView中顯示,但無法找到任何獲得用戶所在街道名稱的方法。有沒有辦法從iOS中的CLLocation獲取街道名稱?

有沒有辦法使用或不使用iOS SDK?

回答

2

從iOS 5開始,您可以使用CLGeocoder來做到這一點。我強烈建議您查看位置感知編程指南,here

爲了得到街道,您應該使用reverseGeocodeLocation:completionHandler:來提出請求。在該完成處理程序中,您將收到一個CLPlacemark對象數組。要獲得街道,只需使用kABPersonAddressStreetKey鍵從CLPlacemark對象的addressDictionary字典中提取對象。

+0

非常感謝!非常有幫助! – BigLex

0

簡單擴展:

import CoreLocation 

typealias StreetNameHandler = (String?) -> Void 

extension CLLocation { 

    func streetNameWithCompletionBlock(completionBlock: StreetNameHandler) { 

     CLGeocoder().reverseGeocodeLocation(self) { placemarks, error in 

      if let addressDictionary = placemarks?.first?.addressDictionary, street = addressDictionary["Street"] as? String { 
       completionBlock(street) 
      } 
     } 
    } 
} 

簡單的用法:

location.streetNameWithCompletionBlock { street in 
    print("street \(street)") 
} 
相關問題