2017-05-22 99 views
0

我正在使用適用於iOS的Google Places API,並且可以成功檢索附近的地點並將地址呈現爲字符串。我想要做的是提取諸如城市之類的地址組件以存儲在數據庫中。如何從GMSPlace地址組件中提取街道,城市等

該文檔表明GMSPlace有一個addressComponents屬性(一個數組),但我似乎無法計算如何使用此屬性。

下面的代碼提供了一系列完整的地址到標籤的文本,但我不能得到超出:

編輯----添加的代碼,顯示如何,我試圖訪問地址組件

venueLabel.isHidden = false 
      venueLabel.text = selectedPlace?.name 
      addressLabel.isHidden = false 
      addressLabel.text = selectedPlace?.formattedAddress 
      let addressComponents = selectedPlace?.addressComponents 
      for component in addressComponents! { 
       let city = component["city"] //Error Type GMSPaceAddressComponent has no subscript members 
       print(city) 
      } 
+0

份額完整的代碼,請。 –

+0

API文檔中提到了所有「addressComponents」的細節。看到這個https://developers.google.com/places/ios-api/reference/interface_g_m_s_place.html#ae0c1f39cee593fcf0909bcdf16ae2761 – Bilal

+0

@Shabirjan剛剛編輯與附加代碼 –

回答

2

selectedPlace.addressComponents是GMSAddressComponent的陣列,其具有2個屬性的類型和名稱。 在你區分它會像

for component in addressComponents! { 
    if component.type == "city" { 
    print(component.name) 
    } 
    } 

GMSAddressComponent是一類不是字典或數組這就是你得到這個錯誤。

其他元件類型可從link中查詢。

+0

謝謝。現在它非常有意義。乾杯! –

0

我找不到這對任何地方的Objective-C,對於那些誰跟着我後面:

for (int i = 0; i < [place.addressComponents count]; i++) 
{ 
    NSLog(@"name %@ = type %@", place.addressComponents[i].name, place.addressComponents[i].type); 
} 
0
for (GMSAddressComponent * component in place.addressComponents) { 
    if ([component.type isEqual: @"locality"]) 
    { 
     NSLog(@"Current city %@ ", component.name); 
    } 
} 
+0

儘管這段代碼可能會回答這個問題,但提供關於爲什麼和/或代碼如何回答問題的其他內容可以提高其長期價值。 –

+0

請解釋您的代碼爲何解決問題。僅有代碼的答案對社區沒有用處。 – JimHawkins

相關問題