Someone selects a marina on the map, switches apps, and comes back an hour later. A fresh search can replace every result on the list. What should still identify the marina they chose?

Location Intelligence, part 1 of 4.

Follow one user through it. They search for a marina, pan to the next bay, type a different query, tap a result, open its details, switch apps, and come back an hour later. During that sequence, search requests finish out of order, the result list is replaced twice, the camera moves for four different reasons, and the app is suspended and restored.

If the map view is the only place where all of that lives (the results in an annotation array, the selection in the map's own selection state, the camera wherever the last animation left it), the feature is hard to test, impossible to show in a list or a widget, and fragile in exactly the ways that sequence exercises.

This series is about location features as engineering. It starts by separating the map, which is a presentation, from the place workflow, which is application state.

A selected place is not its pin

A pin is how one view draws something. The selected place is a fact the application holds, and other parts of the app (the detail sheet, the booking request, state restoration) need it without a map on screen.

So the model is a value the app owns:

SwiftGitHub
import MapKit
import Observation
import SwiftUI

struct Place: Identifiable, Hashable, Sendable {
    enum Origin: Hashable, Sendable {
        case search(providerID: String?)
        case userWaypoint
    }

    let id: UUID
    let name: String
    let latitude: Double
    let longitude: Double
    let origin: Origin

    var coordinate: CLLocationCoordinate2D {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

extension Place {
    init(_ item: MKMapItem) {
        self.init(
            id: UUID(),
            name: item.name ?? "Unnamed place",
            latitude: item.location.coordinate.latitude,
            longitude: item.location.coordinate.longitude,
            origin: .search(providerID: item.identifier?.rawValue)
        )
    }
}

func refreshedMapItem(forProviderID providerID: String) async throws -> MKMapItem? {
    guard let identifier = MKMapItem.Identifier(rawValue: providerID) else {
        return nil
    }
    return try await MKMapItemRequest(mapItemIdentifier: identifier).mapItem
}

Three decisions are encoded here.

Identity is the app's own. id is generated by the app. Coordinates cannot serve as identity: two businesses share a building, and a waypoint the user dropped on a café is a different thing from the café's search result. Equal coordinates mean two things are in the same spot, and nothing more.

Provenance is kept. A place that came from search and one the user created behave differently later. A search result can be refreshed from the provider; a waypoint is the user's own data and is the source of truth for itself.

The provider's identifier is stored as a reference, not as the model. MKMapItem.identifier is the documented way to get back to the same place later, through MKMapItemRequest, and that is what should be persisted. An archived MKMapItem should not be: opening hours, phone numbers, and even names change, and a stored copy goes stale silently. Treat the identifier's stability as a property of the provider that you depend on, handle the case where it no longer resolves, and check the provider's terms before retaining anything beyond it.

MKMapItem is a class and is not Sendable. Mapping to a value type at the boundary is what allows results to cross actors, be compared in tests, and be stored.

Search results need an acceptance check

The user types "coffee", then replaces it with "hospital". Two requests are in flight, and nothing guarantees the first one finishes first. If the last response to arrive wins, the list under the word "hospital" shows coffee shops.

SwiftGitHub
@MainActor
@Observable
final class PlaceSearchModel {
    enum Phase: Equatable {
        case idle
        case searching
        case results([Place])
        case failed
    }

    private(set) var phase: Phase = .idle

    private var generation = 0
    private var activeSearch: MKLocalSearch?

    func search(text: String, region: MKCoordinateRegion) async {
        generation += 1
        let token = generation
        activeSearch?.cancel()
        activeSearch = nil

        let query = text.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !query.isEmpty else {
            phase = .idle
            return
        }

        let request = MKLocalSearch.Request()
        request.naturalLanguageQuery = query
        request.region = region

        let search = MKLocalSearch(request: request)
        activeSearch = search
        phase = .searching

        do {
            let response = try await search.start()
            guard token == generation else { return }
            phase = .results(response.mapItems.map(Place.init))
        } catch {
            guard token == generation else { return }
            phase = .failed
        }
        activeSearch = nil
    }

    func cancel() {
        generation += 1
        activeSearch?.cancel()
        activeSearch = nil
        phase = .idle
    }
}

Every call takes a new generation number before it does anything else, and every result is compared against the current generation before it is published. A response that belongs to an older query is dropped whichever order the network delivers them in.

The explicit activeSearch?.cancel() saves work and quota. It is not the correctness mechanism, for two reasons. MKLocalSearch is an object with its own cancel(), and I do not rely on Swift task cancellation reaching it. And a request that has already completed cannot be cancelled; its result is on the way regardless. The generation check handles both.

Phase is one enum, where the original prototype usually has three properties (results, isSearching, error) that can contradict each other. With one value, "searching and failed at the same time" cannot be represented. It also makes a real distinction visible: .results([]) is a successful search that found nothing, and deserves different copy from .failed.

Debounce is a courtesy; the generation check is the guarantee

Debouncing waits until the user pauses typing before searching. It reduces request volume and saves battery. It does nothing for a request that has already started, so it cannot replace the check above. The two belong in different places: debounce in the input adapter, acceptance in the model.

SwiftGitHub
struct PlaceSearchField: View {
    let model: PlaceSearchModel
    let region: MKCoordinateRegion
    @State private var text = ""

    var body: some View {
        TextField("Search places", text: $text)
            .task(id: text) {
                do {
                    try await Task.sleep(for: .milliseconds(300))
                } catch {
                    return
                }
                await model.search(text: text, region: region)
            }
            .onDisappear { model.cancel() }
    }
}

.task(id:) cancels and restarts its closure every time text changes, so the sleep is interrupted by the next keystroke and only a pause of 300 milliseconds reaches search. No Combine pipeline or timer is needed.

The second input to a search is the region, and it needs a product decision: does moving the map search again? Re-running the query on every camera change produces a list that reshuffles under the user's finger and a stream of requests. A "Search this area" button that appears after the map settles gives the user control. Automatic search once a gesture ends suits some products better. Either is defensible. It should be a decision someone made, visible in a test, and not a side effect of binding the region to the request.

The camera has several owners

Camera movement has at least four sources: the user's gesture, a selected result, follow-my-location mode, and state restoration. Without a rule for which one wins, the app fights the user. The classic version: the user pans away to look at something, a location update arrives, and the map snaps back.

The rule is easier to state once camera intent is separated from camera position:

SwiftGitHub
enum CameraMode: Equatable {
    case followingUser
    case free
    case focused(Place.ID)
}

struct PlaceMap: View {
    let places: [Place]
    @Binding var selection: Place.ID?

    @State private var position: MapCameraPosition = .userLocation(fallback: .automatic)
    @State private var mode: CameraMode = .followingUser

    var body: some View {
        Map(position: $position, selection: $selection) {
            UserAnnotation()
            ForEach(places) { place in
                Marker(place.name, coordinate: place.coordinate)
                    .tag(place.id)
            }
        }
        .onMapCameraChange(frequency: .onEnd) { _ in
            if position.positionedByUser {
                mode = .free
            }
        }
        .onChange(of: selection) { _, newValue in
            guard let place = places.first(where: { $0.id == newValue }) else { return }
            mode = .focused(place.id)
            position = .region(MKCoordinateRegion(
                center: place.coordinate,
                latitudinalMeters: 800,
                longitudinalMeters: 800
            ))
        }
        .overlay(alignment: .bottomTrailing) {
            if mode != .followingUser {
                Button("Recenter", systemImage: "location") {
                    mode = .followingUser
                    position = .userLocation(fallback: .automatic)
                }
                .buttonStyle(.borderedProminent)
                .padding()
            }
        }
    }
}

mode is the intent and position is the outcome. The transitions are few and explicit: a user gesture leaves follow mode, selecting a place focuses it, and the Recenter button is the only way back to following. MapCameraPosition.positionedByUser is what tells a gesture apart from a programmatic change, so the app does not have to infer it from timing.

The selection is a Place.ID owned by the parent. The map never decides what is selected; it reports taps and draws the current value. Panning away from the selected marina does not deselect it, and a camera animation never changes the destination of a booking.

A search region is a hint, not a boundary

request.region tells MapKit where the user is looking. By default it biases results toward that area and may still return places outside it. Setting regionPriority to .required restricts results to the region, which is right for a "search this area" feature.

Neither setting is a business rule. If the product only delivers inside a zone, only lists berths inside a harbor authority's area, or only operates in certain countries, check each result against your own geometry and policy, preferably on the server that will accept the order. The same caution applies to everything MapKit returns. A route estimate is an estimate. A business listing with opening hours is a listing. MapKit supplies evidence, and the claim the app makes to its user on the strength of that evidence is the app's own.

Decide what "offline" means

"Works offline" covers at least four different promises:

  • saved waypoints are still listed;
  • a previously loaded route description can still be read;
  • the map still draws;
  • search and routing still return new results.

The first two depend only on data the app persisted itself, and can be guaranteed. The last depends entirely on the network. The third is the trap: the map may draw from cached tiles during a test in the office and show a blank grid at the actual marina. Do not derive a product promise from that one lucky test. Decide which of the four the product makes, implement those with data the app controls, and present the others as unavailable instead of broken.

The list is part of the feature

A map with thirty small markers is hard to use with VoiceOver, with Switch Control, with limited dexterity, and in bright sunlight on a moving boat. A list of the same results, synchronized with the map, is frequently the better interface for choosing between places, and for some users it is the only workable one.

Because selection is a single Place.ID outside the map, a list and the map stay consistent without extra code: tapping a row and tapping a marker write the same value. If each kept its own selection, VoiceOver would announce one place while the map highlighted another.

Give markers meaningful labels, expose the same actions (directions, save, share) from both presentations, and avoid encoding status in color alone.

A question I use as an architectural check: if the map were replaced by a list tomorrow, how much of the feature would still work? If the answer is "search, selection, details, saving, restoration", the map is a presentation. If the answer is "nothing", the map is holding the application's state.

Test the workflow with a controlled service

The acceptance logic and the camera rules can be tested without Apple's servers. Put a protocol in front of the search call for tests, and cover:

  • query A completes after query B: B's results remain;
  • the query is cleared while a request is in flight: phase is .idle and stays there;
  • a search returns nothing: .results([]), not .failed;
  • cancel() during a search: the late response is ignored;
  • a user gesture during follow mode: mode becomes .free, and later location updates do not move the camera;
  • Recenter: mode returns to .followingUser;
  • restoring a saved selection whose provider identifier no longer resolves.

A fake search service verifies your acceptance policy. It says nothing about the availability or quality of live data, so the device pass still needs airplane mode, a slow connection, denied location permission, and each window size the app supports.

What to ask of your own map feature

  • Where does the selected place live, and can a screen without a map read it?
  • Can a late search response replace the results for a newer query?
  • What changes the camera, and what stops a location update from overriding the user?
  • Is any business rule enforced only by the search region?
  • Which of the four meanings of "offline" has the product promised?

The next part looks at a second source of location, the metadata inside photos, and what is required before an app shares an image with that data removed.

References

If this edition sharpened your next review, you can buy me a coffee.