How to implement auto-complete for address using Apple Map Kit

后端 未结 3 1180
孤独总比滥情好
孤独总比滥情好 2020-11-29 03:06

I want to auto-complete the address for the user as same as what google api provides in this link:

https://developers.google.com/maps/documentation/javascript/places

3条回答
  •  臣服心动
    2020-11-29 03:37

    My answer is fully based on @George McDonnell's. I hope it helps to guys who has troubles with implementing of the last one.

    import UIKit
    import MapKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var searchBar: UISearchBar!
        @IBOutlet weak var tableVIew: UITableView!
    
        //create a completer
        lazy var searchCompleter: MKLocalSearchCompleter = {
            let sC = MKLocalSearchCompleter()
            sC.delegate = self
            return sC
        }()
    
        var searchSource: [String]?
    }
    
    extension ViewController: UISearchBarDelegate {
        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            //change searchCompleter depends on searchBar's text
            if !searchText.isEmpty {
                searchCompleter.queryFragment = searchText
            }
        }
    }
    
    extension ViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return searchSource?.count ?? 0
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            //I've created SearchCell beforehand; it might be your cell type
            let cell = self.tableVIew.dequeueReusableCell(withIdentifier: "SearchCell", for: indexPath) as! SearchCell
    
            cell.label.text = self.searchSource?[indexPath.row]
    //            + " " + searchResult.subtitle
    
            return cell
        }
    }
    
    extension ViewController: MKLocalSearchCompleterDelegate {
        func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
            //get result, transform it to our needs and fill our dataSource
            self.searchSource = completer.results.map { $0.title }
            DispatchQueue.main.async {
                self.tableVIew.reloadData()
            }
        }
    
        func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
            //handle the error
            print(error.localizedDescription)
        }
    }
    

提交回复
热议问题