0

我正在使用 UISearchBar 和 UITableView 执行 MKLocalSearch。

第一次搜索总是很好,但如果你尝试另一个,应用程序崩溃,我得到一个“索引超出范围错误”。如果您需要更多信息,请告诉我,谢谢。

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.searchResults = [] //this might be causing the crash
        print("searchText \(searchText)")
        let searchRequest = MKLocalSearch.Request()
        searchRequest.naturalLanguageQuery = searchText
        
        let search = MKLocalSearch(request: searchRequest)
        search.start { response, error in
            guard let response = response else {
                print("Error: \(error?.localizedDescription ?? "Unknown error").")
                return
            }

            for item in response.mapItems {
                self.searchResults.append(item.placemark)
                self.tableView.reloadData()
            }
        }
    }

}

//MARK: TableView
extension LocationSearchViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchResults.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath)
        let listItem = searchResults[indexPath.row]
        cell.textLabel?.text = listItem.name
        cell.detailTextLabel?.text = listItem.administrativeArea ?? ""

        return cell
    }
    

}

extension LocationSearchViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected a row")
        let local = searchResults[indexPath.row]
 
        // pass local back
        if let delegate = delegate{
            delegate.doSomethingWith(data: local)
        }
        
        
        dismiss(animated: true, completion: nil)
    }
}

在第 3 次或第 4 次尝试搜索后,表中的结果保持不变,不再记录任何结果。我得到错误:

错误:操作无法完成。(MKErrorDomain 错误 3。)

4

1 回答 1

1

您的问题是您更改 searchResults 太早了。尝试:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    print("searchText \(searchText)")
    let searchRequest = MKLocalSearch.Request()
    searchRequest.naturalLanguageQuery = searchText
    
    let search = MKLocalSearch(request: searchRequest)
    search.start { response, error in
        guard let response = response else {
            print("Error: \(error?.localizedDescription ?? "Unknown error").")
            return
        }
        var newArray: [YourStruct] = []
        for item in response.mapItems {
            newArray.append(item.placemark)
            
        }
        self.searchResults = newArray
        self.tableView.reloadData()
    }
}
于 2020-09-03T13:19:12.850 回答