How to extract street, city, etc. from GMSPlace Address Components

后端 未结 10 1705
栀梦
栀梦 2021-02-20 02:51

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

10条回答
  •  醉梦人生
    2021-02-20 03:35

    I will extend @Ramis answer, in any case you want to check for multiple types if one of them exist, e.x

    addressComponents?.valueFor(placeTypes: kGMSPlaceTypePostalTown, kGMSPlaceTypeLocality)
    

    implementation

    extension Array where Element == GMSAddressComponent {
        func valueFor(placeTypes: String..., shortName: Bool = false) -> String? {
            let array = self as NSArray
            let result = array
                .compactMap { $0 as? GMSAddressComponent }
                .first(where: {
                    placeTypes.contains($0.types.first(where: { placeTypes.contains($0) }) ?? "")
                })
            return shortName ? result?.shortName : result?.name
        }
    }
    

提交回复
热议问题