애플 공식 문서를 참고해보세요!
Display map or satellite imagery within your app, call out points of interest, and determine placemark information for map coordinates.
MapKit
을 이용하면 앱 내에서 지도 또는 위성 이미지를 표시하고 원하는 지점을 호출할수 있으며 지도 좌표에 대한 장소 정보를 확인할 수 있습니다.
private var searchCompleter = MKLocalSearchCompleter()
private var searchRegion: MKCoordinateRegion = MKCoordinateRegion(MKMapRect.world)
private var searchResults = [MKLocalSearchCompletion]()
private var places: MKMapItem? {
didSet {
resultTableView.reloadData()
}
}
private var localSearch: MKLocalSearch? {
willSet {
// Clear the results and cancel the currently running local search before starting a new search.
places = nil
localSearch?.cancel()
}
}
searchCompleter.delegate = self
searchCompleter.resultTypes = .address
searchCompleter.region = searchRegion
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
searchResults.removeAll()
resultTableView.reloadData()
}
searchCompleter.queryFragment = searchText
}
}
searchCompleter
에 검색문자 searchText
를 넣어줍니다.
extension SearchViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
searchResults = completer.results
resultTableView.reloadData()
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
if let error = error as NSError? {
print("MKLocalSearchCompleter encountered an error: \(error.localizedDescription). The query fragment is: \"\(completer.queryFragment)\"")
}
}
}
response는 mapItems등을 담고있어요!
저는 경도 위도를 사용하여 날씨를 받아오는 api를 사용하였기 때문에 lat: placemark.coordinate.latitude, lon: placemark.coordinate.longitude
로 경도 위도를 받아왔습니다.
extension SearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedResult = searchResults[indexPath.row]
let searchRequest = MKLocalSearch.Request(completion: selectedResult)
let search = MKLocalSearch(request: searchRequest)
search.start { response, error in
guard error == nil else {
return
}
guard let placemark = response?.mapItems[0].placemark else { return }
self.requestGetWeather(lat: placemark.coordinate.latitude, lon: placemark.coordinate.longitude, location: (placemark.locality ?? placemark.title) ?? "")
}
}
}
extension SearchViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let searchResult = searchResults[indexPath.row]
cell.textLabel?.font = .systemFont(ofSize: 16)
cell.textLabel?.textColor = .gray
cell.backgroundColor = .clear
if let highlightText = searchBar.text {
cell.textLabel?.setHighlighted(searchResult.title, with: highlightText)
}
return cell
}
}
extension UILabel {
func setHighlighted(_ text: String, with search: String) {
let attributedText = NSMutableAttributedString(string: text)
let range = NSString(string: text).range(of: search, options: .caseInsensitive)
let highlightFont = UIFont.systemFont(ofSize: 16)
let highlightColor = UIColor.white
let highlightedAttributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.font: highlightFont, NSAttributedString.Key.foregroundColor: highlightColor]
attributedText.addAttributes(highlightedAttributes, range: range)
self.attributedText = attributedText
}
}
let textFieldInsideSearchBar = $0.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.textColor = .white