0

我得到了一个 SearchBar,它给出了它打印在 TableView 中搜索的名称的名称。在添加搜索的键之前,我正在检查我的数据库是否获得了变量。如果我的数据库得到它,我会在 TableView 中添加搜索到的单词。我的问题是,目前matchingItems 或response.mapItems 有双变量或更多变量,并且它在TableView 中打印了很多次相同的名称。我已经尝试了很多时间来解决这个问题,但我不知道该怎么做。

错误图片 > http://i67.tinypic.com/2jfyxdf.png MKMapItem 示例

<MKMapItem: 0x6000003566e0> {
isCurrentLocation = 0;
name = "Arco di Traiano";
placemark = "Arco di Traiano, Via Traiano, 82100 Benevento, Italia @ <+41.13253257,+14.77915406> +/- 0.00m, region CLCircularRegion (identifier:'<+41.13253316,+14.77915406> radius 1414.16', center:<+41.13253316,+14.77915406>, radius:1414.16m)";
timeZone = "Europe/Rome (CEST) offset 7200 (Daylight)";
url = "http://www.comune.benevento.it/bn2_pagine/_mediagallery/pid.php?id=11";
}

代码是这样的:

var matchingItems: [MKMapItem] = []

extension LocationSearchTable : UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {

        if searchController.searchBar.text == nil || (searchController.searchBar.text?.count)! < 1 {
            self.matchingItems.removeAll()
            self.tableView.reloadData()
        }

        guard let mapView = mapView,
            let searchBarText = searchController.searchBar.text else { return }

        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchBarText
        request.region = mapView.region
        let search = MKLocalSearch(request: request)

        search.start { response, _ in
            guard let response = response else {
                return
            }
            for (index , name) in response.mapItems.enumerated() {

            if (checkIfDatabaseGotThis(key: String(name.name!)) != nil){
                self.matchingItems.append(response.mapItems[index])
                self.tableView.reloadData()
            }

        }
    }
}
}
4

1 回答 1

0

更新后,示例按名称进行重复数据删除:

var seenNames = Set<String>()
for (index , name) in response.mapItems.enumerated() {
    let item = response.mapItems[index]
    if(checkIfDatabaseGotThis(key: String(name.name!)) != nil && !seenNames.contains(item.name)){
        self.matchingItems.append(item)
        seenNames.insert(item.name)
        self.tableView.reloadData()
    }
}

That should remove all duplicates from your list of items based on the name. It keeps track of all the existing names that you have seen. If the name hasn't been seen before, the item is added to the list. Otherwise it is ignored.

于 2018-06-12T08:57:53.867 回答