AdvenShare is an app for off-road racing and overland teams. People press Record at the edge of a desert, drive for hours with no signal, and expect the route to be on the server afterwards. Sometimes there is no network when they press Record. Sometimes the app is killed halfway.
The short answer to how the iOS app handles that: a recorded point is never sent straight to the network. Every accepted GPS fix is written to a local SQLite table first, and a separate sync loop uploads rows in batches of up to 500 and deletes them only when the server acknowledges them by id. If the route could not be created on the server, it records under a temporary id and is registered later. A small state record in UserDefaults lets the next launch resume a recording that was cut off less than 10 minutes ago, or close it properly if it is older.
Recording GPS points to SQLite before anything else
The recorder has one write path, online or offline.
func emitRoutePoint(routeId: String, location: CLLocation) {
guard let userId = authManager.currentUser?.id else { return }
let originalTimestamp = location.timestamp
routePointStore.add(
routeId: routeId,
latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
timestamp: originalTimestamp,
userId: userId
)
}
The store is plain SQLite3 in the Application Support directory, opened in WAL mode (write-ahead logging, where writes append to a log instead of rewriting the database file). The table is pending_route_points: a UUID primary key, route id, user id, latitude, longitude and a timestamp in milliseconds. All access goes through one serial dispatch queue.
Two details matter. The timestamp is the one Core Location put on the fix, not the time of the write, so a point uploaded hours late still sits in the right place on the timeline. And the row id is generated on the phone, which makes acknowledgement by id possible later.
While recording, CLLocationManager runs with kCLLocationAccuracyBest, a distanceFilter of 5 metres, pausesLocationUpdatesAutomatically off and allowsBackgroundLocationUpdates on, with the location background mode declared.
Filtering noisy GPS fixes while the receiver warms up
Not every fix becomes a point. A fix is dropped if its horizontal accuracy is worse than 15 metres, or if it is less than 3 metres from the last accepted point. For the first 90 seconds of a route those limits are relaxed to 50 metres and 1.5 metres, so the start of a route is not lost while the GPS stabilises.
let inWarmUp: Bool = {
if let start = self.routeWarmUpStartTime {
return Date().timeIntervalSince(start) < self.warmUpDurationSeconds
}
return false
}()
let accuracyThreshold: CLLocationAccuracy = inWarmUp ? 50.0 : 15.0
let distanceThreshold: CLLocationDistance = inWarmUp ? 1.5 : 3.0
let isAccurate = currentLocation.horizontalAccuracy <= accuracyThreshold
guard isAccurate else { return }
iOS can also deliver several fixes in one didUpdateLocations call. The location manager publishes the newest one and hands the rest to the recorder, which sorts them by timestamp and runs them through the same filter.
Starting a route with no network: temporary route ids
A route needs a server id, and creating one is an HTTP request. If that request fails, recording starts anyway under a local id.
private func startOfflineTracking(at location: CLLocation, startTime: Date) {
let tempRouteId = "temp_\(UUID().uuidString)"
currentTemporaryRouteId = tempRouteId
pendingRouteRegistrations.append((location: location, endLocation: nil,
startTime: startTime, tempRouteId: tempRouteId))
isTracking = true
isOfflineTracking = true
routePoints = [location.coordinate]
emitRoutePoint(routeId: tempRouteId, location: location)
subscribeToLocationUpdates(routeId: tempRouteId)
}
Points are stored against temp_… exactly like any other route. When the socket reconnects, the app retries the create call with the original start time. On success, one SQL UPDATE rewrites the route id on every stored row from the temporary id to the real one. A failed registration retries with exponential backoff: 2, 4, 8, 16, 32 seconds, then capped at 60.
The list of pending registrations lives in memory, but it is rebuilt at launch from the database: any temp_ route id still in the table becomes a pending registration, with its start location and start time taken from its earliest stored point.
If the user presses Stop while still offline, the route cannot be ended on the server because it does not exist there yet. The temporary id is added to a set persisted in UserDefaults, and the end event is sent after registration.
Syncing recorded points when the network returns
Sync is triggered when the socket connects, when the app returns to the foreground, when recording stops, and by a 30-second timer that cancels itself once the table is empty.
Each pass reads the oldest 500 rows for the signed-in user, with two exclusions:
var excludeRouteIds = self.skippedRouteIds
let trackingManager = RouteTrackingManager.shared
if trackingManager.isTracking, let activeRouteId = trackingManager.getCurrentActiveRouteId() {
excludeRouteIds.insert(activeRouteId)
}
let batch = store.fetchBatchExcludingRoutes(limit: 500, userId: userId,
excludeRouteIds: excludeRouteIds)
// Temp routes must be registered first (points will be migrated)
let filteredBatch = batch.filter { !$0.routeId.hasPrefix("temp_") }
The batch is emitted over the socket, and the server replies with an acknowledgement listing the ids it stored. Only those rows are deleted. If exactly 500 came back, another pass runs half a second later. If no acknowledgement arrives in 30 seconds, the rows stay where they are and the pass retries with the same capped backoff.
Ending a route waits for the same loop: the stop handler polls every 2 seconds until the store has no rows left for that route and no sync is in flight, then emits the end event.
Recovering a route after a crash or the app being killed
The points are already on disk. What dies with the process is the knowledge that a recording was in progress. I added recovery about a month after offline tracking.
Each time a point is accepted, the recorder saves a small Codable struct to UserDefaults: the real or temporary route id, whether it was offline, the start time, the start coordinate and the time of this update. Stop clears it.
Two seconds after launch, the recorder looks for that record and decides by its age:
let timeSinceLastUpdate = Date().timeIntervalSince(savedState.lastUpdateTime)
if timeSinceLastUpdate > 86400 { // 24 hours
clearActiveRouteState()
return
}
if timeSinceLastUpdate > 600 { // 10 minutes
handleStaleRouteRecovery(savedState: savedState)
return
}
handleActiveRouteRecovery(savedState: savedState)
Under 10 minutes, the route resumes under the same id. The app switches back to high-accuracy updates, ignores fixes for 5 seconds while the GPS settles, then continues recording from the current location. It gives up if there is no fix or the reported accuracy is worse than 1,000 metres.
Between 10 minutes and 24 hours, the route is not resumed. Its stored points are synced and it is ended on the server, or queued to end after registration if it only ever had a temporary id. Past 24 hours the record is discarded as untrustworthy.
Trade-offs and what broke along the way
The active route is not uploaded while it is being recorded. Its points sync after Stop. The sync loop never races the recorder or the id rewrite, but the server has nothing for a route until the recording ends. Live position sharing with teammates is a separate socket event.
A rejected batch does not say which route was at fault. The app blames the first route in the oldest batch. A foreign-key error from the server deletes that route's local points at once, since the route does not exist there. Any other rejection puts the route on a skip list for 5 minutes, and after 3 rejections its points are deleted. Timeouts and disconnects never count toward that limit. This is deliberate data loss so that one bad route cannot block everything behind it.
Several offline routes in a row broke the first version. The early history is mostly fixes for multiple queued routes: registering them one at a time and waiting for a sync to finish before the next. Duplicate routes came later, fixed by a single guard so that two code paths cannot create a route at the same time when the network flickers.
Recovery leaves a gap. Nothing is recorded between the kill and the user reopening the app, and the resumed trail on screen starts from the current location.
Takeaways
- Write every GPS point to local storage first and treat upload as a separate job that reads from that storage.
- Delete a local row only when the server acknowledges that row's id, so a timeout is always safe to retry.
- Give a route a temporary local id when it cannot be created online, and rewrite the id on stored rows once it can.
- Persist a small "recording in progress" record with a last-update time, and use its age to choose between resuming and ending.
- Count only explicit server rejections toward giving up on data, never network failures.