はじめに
MKLocalSearchCompleterを使用して場所の検索をローカルで行うことができるっぽいので試してみました。
サンプルアプリ
実装
import SwiftUI
struct ContentView: View {
@StateObject private var viewState = ViewState()
var body: some View {
NavigationStack {
List(viewState.localSearchCompletions, id: \.self) { localSearchCompletion in
Text(localSearchCompletion.title)
}
.searchable(text: $viewState.searchText)
}
}
}
import MapKit
import Combine
public final class ViewState: NSObject, ObservableObject {
@Published var searchText = ""
@Published var localSearchCompletions: [MKLocalSearchCompletion] = []
private let localSearchCompleter = MKLocalSearchCompleter()
private var cancellable = Set<AnyCancellable>()
public override init() {
super.init()
localSearchCompleter.delegate = self
$searchText.sink {
self.localSearchCompleter.queryFragment = $0
}
.store(in: &cancellable)
}
}
extension ViewState: MKLocalSearchCompleterDelegate {
public func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
self.localSearchCompletions = completer.results
}
}
おわり
通信しなくていいのはめっちゃいいですね!