在我的应用程序中,我需要用户输入他的家庭住址,但我无法确定所显示的地址仅在用户区域中,并且是完整地址,例如225e 57th st, NY, New York
。< / p>
我想在桌面视图中为用户提供所有列出的选项,并在用户输入他的地址时对其进行过滤。
答案 0 :(得分:7)
您可以定义local search completer:
let completer = MKLocalSearchCompleter()
然后提供查询片段:
completer.delegate = self
completer.region = MKCoordinateRegion(center: currentCoordinate, latitudinalMeters: 10_000, longitudinalMeters: 10_000)
completer.queryFragment = "300 S Orange"
实施MKLocalSearchCompleterDelegate
协议
extension ViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
let addresses = completer.results.map { result in
result.title + ", " + result.subtitle
}
// use addresses, e.g. update model and call `tableView.reloadData()
}
}
然后产生:
["300 S Orange Grove Blvd, Pasadena, CA, United States", "300 S Orange Ave, Monterey Park, CA, United States", "300 S Orange St, Glendale, CA, United States", "300 S Orange Dr, Los Angeles, CA, United States", "300 S Orange Ave, Azusa, CA, United States", "300 S Orange Grove Ave, Los Angeles, CA, United States", "300 S Orange Ave, Brea, CA, United States", "300 S Orange Ave, Fullerton, CA, United States", "300 S Orange St, Orange, CA, United States", "300 S Orange Ave, Rialto, CA, United States", "300 S Orange Ave, Fallbrook, CA, United States", "300 S Orange St, Escondido, CA, United States", "300 S Orange Ave, El Cajon, CA, United States", "300 S Orange Cir, Tulare, CA, United States", "300 S Orange Ave, Exeter, CA, United States"]
否则,您可以进行本地搜索:
let request = MKLocalSearch.Request()
request.region = MKCoordinateRegion(center: currentCoordinate, latitudinalMeters: 10_000, longitudinalMeters: 10_000)
request.naturalLanguageQuery = "300 S Pumpkin"
let formatter = CNPostalAddressFormatter()
formatter.style = .mailingAddress
let search = MKLocalSearch(request: request)
search.start { response, error in
let addresses = response?.mapItems.compactMap { item -> String? in
return item.placemark.postalAddress.flatMap {
formatter.string(from: $0).replacingOccurrences(of: "\n", with: ", ")
}
}
print(addresses)
}
现在,我正在使用Contacts框架的格式化程序(它也公开了地标上的postalAddress
属性),但您可以按照您想要的任何方式格式化这些格式。但是,假设它找到匹配,则表示类似:
["300 S Pumpkin Blvd, Los Angeles, CA 92108, United States", "300 S Pumpkin Pkwy, Los Angeles, CA 92103, United States", "300 S Pumpkin Dr, San Gabriel, CA 91776, United States"])
现在,无论您是想要FormattedAddressLines
,还是从addressDictionary
中提取单个组件,都取决于您,但希望这可以说明这一点。