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

后端 未结 10 1902
栀梦
栀梦 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:46

    I am using this extension:

    extension Array where Element == GMSAddressComponent {
        func valueFor(placeType: String, shortName: Bool = false) -> String? {
            // bug in the google or apple framework. This cast must stay.
            // Withou it crashing.
            guard let array = self as? NSArray else { return nil }
            let result = array
                .compactMap { $0 as? GMSAddressComponent }
                .first(where: {
                    $0.types
                        .first(where: { $0 == placeType }) == placeType
                })
            return shortName ? result?.shortName : result?.name
        }
    }
    

    Usage:

    let place: GMSPlace
    // ...
    place.addressComponents?.valueFor(placeType: kGMSPlaceTypeRoute, shortName: true)
    

提交回复
热议问题