使用 Combine 和 SwiftUI (Swift 5.3) 进行测试。
这不是完美的解决方案,但你只能得到城市和国家:
MKLocalSearchCompleter 的设置:
searchCompleter = MKLocalSearchCompleter()
searchCompleter.delegate = self
searchCompleter.region = MKCoordinateRegion(.world)
searchCompleter.resultTypes = MKLocalSearchCompleter.ResultType([.address])
在委托方法中添加的代码:
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))
}
request.resultTypes = .address
。这将仅设置地址为您的结果。 - user2023106