我正在尝试构建一个简单的天气应用程序,但在尝试实现搜索城市功能时遇到了困难。我设法实现了搜索功能以返回 CLPlacemarks 列表,但是,这包括很多兴趣点(例如餐馆、街道名称......),这使得结果非常困惑。有没有办法将结果限制为仅具有该名称的城市?这是我的代码:
func updateSearchResults(for searchController: UISearchController) {
var searchText = searchController.searchBar.text
request.naturalLanguageQuery = searchText
localSearch = MKLocalSearch(request: request)
localSearch?.start { (searchResponse, _) in
guard let items = searchResponse?.mapItems else {
return
}
self.placemarks = [CLPlacemark]()
for pm in items {
self.placemarks.append(pm.placemark)
}
}
}
最佳答案
使用 Combine 和 SwiftUI (Swift 5.3) 进行测试
这不是完美的解决方案,但或多或少你只能得到城市和国家:
MKLocalSearchCompleter 设置:
searchCompleter = MKLocalSearchCompleter()
searchCompleter.delegate = self
searchCompleter.region = MKCoordinateRegion(.world)
searchCompleter.resultTypes = MKLocalSearchCompleter.ResultType([.address])
在委托(delegate)方法上添加的代码:
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
let searchResults = self.getCityList(results: completer.results)
print(searchResults)
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
print(error.localizedDescription)
}
获取城市:
func getCityList(results: [MKLocalSearchCompletion]) -> [(city: String, country: String)]{
var searchResults: [(city: String, country: String)] = []
for result in results {
let titleComponents = result.title.components(separatedBy: ", ")
let subtitleComponents = result.subtitle.components(separatedBy: ", ")
buildCityTypeA(titleComponents, subtitleComponents){place in
if place.city != "" && place.country != ""{
searchResults.append(place)
}
}
buildCityTypeB(titleComponents, subtitleComponents){place in
if place.city != "" && place.country != ""{
searchResults.append(place)
}
}
}
return searchResults
}
您可以获得两种类型的城市:
func buildCityTypeA(_ title: [String],_ subtitle: [String], _ completion: @escaping ((city: String, country: String)) -> Void){
var city: String = ""
var country: String = ""
if title.count > 1 && subtitle.count >= 1 {
city = title.first!
country = subtitle.count == 1 && subtitle[0] != "" ? subtitle.first! : title.last!
}
completion((city, country))
}
func buildCityTypeB(_ title: [String],_ subtitle: [String], _ completion: @escaping ((city: String, country: String)) -> Void){
var city: String = ""
var country: String = ""
if title.count >= 1 && subtitle.count == 1 {
city = title.first!
country = subtitle.last!
}
completion((city, country))
}
👍
关于swift - 如何在 MapKit、Swift 5 中搜索城市?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62703042/