orim553 orim553 -4 years ago 105
iOS Question

Search for address using SWIFT

In my app I need the user to enter his home address, but I can't get any way that the addresses that are shown are only in the users region, and are full addresses, like

225e 57th st, NY, New York
.

I want to give the user all the listed options on a tableview, and to filter them as the user enters his address.

Answer Source

You can define a local search completer:

let completer = MKLocalSearchCompleter()

And then supply the query fragment:

completer.delegate = self
completer.region = MKCoordinateRegionMakeWithDistance(currentCoordinate, 10_000, 10_000)
completer.queryFragment = "300 S Orange"

And implement the MKLocalSearchCompleterDelegate protocol

extension ViewController: MKLocalSearchCompleterDelegate {

    func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
        let addresses = completer.results.map { result in
            result.title + ", " + result.subtitle
        }

        // use addresses, e.g. update model and call `tableView.reloadData()
    }

}

And that yields:

["300 S Orange Grove Blvd, Pasadena, CA, United States",
 "300 S Orange Ave, Monterey Park, CA, United States",
 "300 S Orange St, Glendale, CA, United States",
 "300 S Orange Dr, Los Angeles, CA, United States",
 "300 S Orange Ave, Azusa, CA, United States",
 "300 S Orange Grove Ave, Los Angeles, CA, United States",
 "300 S Orange Ave, Brea, CA, United States",
 "300 S Orange Ave, Fullerton, CA, United States",
 "300 S Orange St, Orange, CA, United States",
 "300 S Orange Ave, Rialto, CA, United States",
 "300 S Orange Ave, Fallbrook, CA, United States",
 "300 S Orange St, Escondido, CA, United States",
 "300 S Orange Ave, El Cajon, CA, United States",
 "300 S Orange Cir, Tulare, CA, United States",
 "300 S Orange Ave, Exeter, CA, United States"]

Or else, you can do a local search:

let request = MKLocalSearchRequest()
request.region = MKCoordinateRegionMakeWithDistance(currentCoordinate, 10_000, 10_000)
request.naturalLanguageQuery = "300 S Pumpkin"

let search = MKLocalSearch(request: request)
search.start { response, error in
    let addresses = response?.mapItems.map { item -> String in
        if let addressLines = item.placemark.addressDictionary?["FormattedAddressLines"] as? [String] {
            return addressLines.joined(separator: " ")
        }
        return item.name ?? "Unknown"
    }
    print(addresses)
}

Assuming it finds matches, that shows something like:

["300 S Pumpkin Blvd, Los Angeles, CA  92108, United States",
 "300 S Pumpkin Pkwy, Los Angeles, CA  92103, United States",
 "300 S Pumpkin Dr, San Gabriel, CA  91776, United States"])

Now, whether you want the FormattedAddressLines, or extract the individual components from the addressDictionary is up to you, but hopefully this illustrates the idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download