π΄ Let's Build UBER with SwiftUI | iOS 16 & Xcode 14
UberClone: Location Select
ꡬν λͺ©ν
- μ νν μ§μμΌλ‘ λ·° μ΄λ
ꡬν νμ€ν¬
- λ·° λͺ¨λΈμ νκ²½ λ³μν β μ§μ κ²μ, ν λ·° λ±μμ μ 체μ μΌλ‘ λμΌν μΈμ€ν΄μ€ μ κ·Ό 보μ₯
- μ§μ κ²μ κ²°κ³Ό μ°κ²°
- μ΄λ
Έν
μ΄μ
μ€μ λ° νμ¬ λ³΄μ΄λ μ§μμΌλ‘ UI μ΄λ
ν΅μ¬ μ½λ
import SwiftUI
@main
struct UberCloneApp: App {
@StateObject private var locationViewModel = LocationSearchViewModel()
var body: some Scene {
WindowGroup {
HomeView()
.environmentObject(locationViewModel)
}
}
}
- νκ²½ λ³μλ‘ λ·° λͺ¨λΈ μ κ·Ό κ°λ₯
func selectLocation(with location: MKLocalSearchCompletion) {
locationSearch(with: location) { [weak self] response, error in
guard
error == nil,
let item = response?.mapItems.first else { return }
let coordinate = item.placemark.coordinate
self?.selectedLocation = coordinate
}
}
- λ·° λͺ¨λΈ λ΄ νΉμ μ§μμ κ²μνλ ν¨μ
private func locationSearch(with localSearch: MKLocalSearchCompletion, completion: @escaping MKLocalSearch.CompletionHandler) {
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = localSearch.title + localSearch.subtitle
let search = MKLocalSearch(request: searchRequest)
search.start(completionHandler: completion)
}
- κΈ°λ³Έμ μΌλ‘ μ 곡νλ νΈλ€λ¬λ₯Ό μ λ¬
func updateUIView(_ uiView: UIViewType, context: Context) {
if let selectedLocation = viewModel.selectedLocation {
context.coordinator.addAndSelectAnnotation(with: selectedLocation)
}
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
setRegion(with: userLocation.coordinate)
}
private func setRegion(with coordinate: CLLocationCoordinate2D) {
let region = MKCoordinateRegion(center: coordinate, span: .init(latitudeDelta: 0.05, longitudeDelta: 0.05))
parent.mapView.setRegion(region, animated: true)
}
func addAndSelectAnnotation(with coordinate: CLLocationCoordinate2D) {
parent.mapView.removeAnnotations(parent.mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
parent.mapView.addAnnotation(annotation)
parent.mapView.selectAnnotation(annotation, animated: true)
parent.mapView.showAnnotations(parent.mapView.annotations, animated: true)
setRegion(with: coordinate)
}
.onTapGesture {
withAnimation(.spring()) {
viewModel.selectLocation(with: result)
showLocationSearchView.toggle()
}
}
ꡬν νλ©΄