3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

【Swift】MapKitを使用して場所のサジェストを受け取る

Posted at

はじめに

MKLocalSearchCompleterを使用して場所の検索をローカルで行うことができるっぽいので試してみました。

サンプルアプリ

Simulator Screen Recording - iPhone 14 - 2023-07-13 at 19.43.24.gif

実装

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
    }
}

おわり

通信しなくていいのはめっちゃいいですね!

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?