swift - 如何在 MapKit、Swift 5 中搜索城市?

标签 swift search location mapkit city

我正在尝试构建一个简单的天气应用程序,但在尝试实现搜索城市功能时遇到了困难。我设法实现了搜索功能以返回 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)
        }
    }
}

最佳答案

使用 CombineSwiftUI (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/

相关文章:

javascript - PHP - 在数据库中使用一个输入进行搜索

java - 在 Android 上搜索 SQLite 数据库

php - 如何在数组键中搜索子字符串?

ios - SwiftUI Gradient 在模拟器上渲染不正确的颜色

ios - 在 Swift 中设置 UIDatePicker 的文本颜色

ios - 分配 NSTimer 时不调用 Deinit

mysql - 如何在MySQL中用公里搜索附近的位置

javascript - AngularJS $location.path 未按预期工作

没有 Activity 的Android Context?和其他无 Activity 编程?

arrays - 将 String 转换为 Double 并检查是否为 nil