如何从GMSPlace地址组件中提取街道,城市等 [英] How to extract street, city, etc. from GMSPlace Address Components

查看:139
本文介绍了如何从GMSPlace地址组件中提取街道,城市等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iOS版Google Places API,可以成功检索附近的地点并将地址显示为字符串.我正在尝试提取地址成分(例如城市)以存储在数据库中.

文档表明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)
            }

解决方案

安全的Swift 4.2解决方案:

let name = place.addressComponents?.first(where: { $0.type == "city" })?.name


selectedPlace.addressComponents是 GMSAddressComponent 的数组,具有2个属性类型和名称. 在您的情况下,它将类似于

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

GMSAddressComponent是一个类,而不是字典或数组,这是您遇到此错误的原因.

可以从链接中引用其他组件类型.. >

I'm using Google Places API for iOS and can successfully retrieve nearby places and present the address as a string. What I'm trying to do is extract address components such as city to store in a database.

The documentation indicates a GMSPlace has an addressComponents property (an array), but I can't seem to figure how to use this property.

The code below provides sets the entire address to the text of a label, but I can't get beyond that:

Edit ---- added code that shows how I'm trying to access Address Components

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)
            }

解决方案

A safe Swift 4.2 solution:

let name = place.addressComponents?.first(where: { $0.type == "city" })?.name


selectedPlace.addressComponents is a array of GMSAddressComponent which have 2 properties type and name. In you case it will be like

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

GMSAddressComponent is a class not a dictionary or array that's you are getting this error.

Additional component types can be referred from the link.

这篇关于如何从GMSPlace地址组件中提取街道,城市等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆