[SwiftUI] UberClone: Location Search Logic

Junyoung Parkยท2022๋…„ 11์›” 19์ผ
0

SwiftUI

๋ชฉ๋ก ๋ณด๊ธฐ
113/136
post-thumbnail
post-custom-banner

๐Ÿ”ด Let's Build UBER with SwiftUI | iOS 16 & Xcode 14

UberClone: Location Search Logic

๊ตฌํ˜„ ๋ชฉํ‘œ

  • ์ฟผ๋ฆฌ ํ…์ŠคํŠธ๋ฅผ ํ†ตํ•ด ์ง€์—ญ ๊ฒ€์ƒ‰

๊ตฌํ˜„ ํƒœ์Šคํฌ

  • ๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ ํ…์ŠคํŠธ๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ๋ทฐ ๋ชจ๋ธ
  • ํ…์ŠคํŠธ๋ฅผ ํ†ตํ•ด ์‹ค์‹œ๊ฐ„์œผ๋กœ ๊ฒ€์ƒ‰ ๊ธฐ๋Šฅ ๊ตฌํ˜„

ํ•ต์‹ฌ ์ฝ”๋“œ

import Foundation
import MapKit
import Combine

class LocationSearchViewModel: NSObject, ObservableObject {
    @Published var results = [MKLocalSearchCompletion]()
    private let searchCompleter = MKLocalSearchCompleter()
    @Published var queryFragment: String = ""
    private var cancellables = Set<AnyCancellable>()
    
    override init() {
        super.init()
        searchCompleter.delegate = self
        bind()
    }
    
    private func bind() {
        $queryFragment
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
            .sink { [weak self] query in
                self?.searchCompleter.queryFragment = query
            }
            .store(in: &cancellables)
    }
    
}

extension LocationSearchViewModel: MKLocalSearchCompleterDelegate {
    func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
        results = completer.results
    }
}
  • ObseravleObject๋กœ ์„ ์–ธํ•œ ๋ทฐ ๋ชจ๋ธ
  • ํ•ด๋‹น ๋ทฐ์—์„œ @StateObject๋กœ ๋ฐ›์„ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ’ ๋ณ€ํ™” ํฌ์ฐฉ ๊ฐ€๋Šฅ
  • ๋ทฐ ํ…์ŠคํŠธ ํ•„๋“œ์˜ ํ˜„์žฌ ์‹ค์‹œ๊ฐ„ ํ…์ŠคํŠธ๋ฅผ queryFragment์— ์—ฐ๋™ โ†’ ์ปด๋ฐ”์ธ์˜ debounce๋ฅผ ํ†ตํ•ด 0.5 ์ดˆ ๋™์•ˆ ์ธํ’‹์ด ์—†์„ ๋•Œ sink ํ•˜๋‹จ์œผ๋กœ ๋ฐ์ดํ„ฐ๊ฐ€ ํ˜๋Ÿฌ๊ฐ€๋„๋ก ๊ตฌ์กฐํ™”
  • MKLocalSearchCompleter์˜ ๋ธ๋ฆฌ๊ฒŒ์ดํŠธ ํ•จ์ˆ˜ completerDidUpdateResults๋ฅผ ํ†ตํ•ด ์ฟผ๋ฆฌ ๊ฒ€์ƒ‰์„ ํ†ตํ•œ ๊ฒฐ๊ณผ๋ฅผ ๊ณง๋ฐ”๋กœ ์—…๋ฐ์ดํŠธ ๊ฐ€๋Šฅ
    @StateObject private var viewModel = LocationSearchViewModel()
...
TextField("Where to?", text: $viewModel.queryFragment, axis: .vertical)
                        .frame(minHeight: 32)
                        .background(Color(.systemGray4))
                        .padding(.trailing)
  • ๋„์ฐฉ์ง€๋ฅผ ๋ฌผ์–ด๋ณด๋Š” ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ๋ทฐ์˜ ํ…์ŠคํŠธ ํ•„๋“œ์˜ ๋ฐ์ดํ„ฐ ์†Œ์Šค๋ฅผ ํ•ด๋‹น ๋ทฐ ๋ชจ๋ธ์˜ ์ฟผ๋ฆฌ ํ…์ŠคํŠธ์™€ ๋ฐ”์ธ๋”ฉ

๊ตฌํ˜„ ํ™”๋ฉด

profile
JUST DO IT
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€