PublicTransport for Swift
A Swift client for public transport APIs. It uses a shared model for stops, departures and trips that covers several server types, so an application can query any supported network the same way. It supports servers that speak EFA (used by many German transport associations), MOTIS (the routing engine behind Transitous), TRIAS 1.2, OJP 1.0, HAFAS mgate (the interface behind many operators’ apps) and OpenTripPlanner 2 with its Transmodel API.
The package wraps the Rust library of the same name. The Rust code builds the requests and parses the answers, and URLSession sends them. It runs on iOS, macOS, tvOS, watchOS and visionOS from version 26, and on Linux.
Add it to a project by the URL of this repository, and depend on a version:
.package(url: "https://github.com/kiliankoe/publictransport", from: "0.1.2")
On Apple platforms the package downloads the Rust library as a binary from the release. Between releases the code on a branch can be ahead of that binary, so a dependency on a branch does not work. On Linux the package links the library from a directory you name, see “Development”. On watchOS the library covers only the watches with a 64-bit processor (Series 9 and later), so an app for all watches does not link yet.
import PublicTransport
let client = Client(userAgent: "my-app/1.0 (+https://example.org)")
let network = Network.bundled(.vvoEfa)
let stops = try await client.locations(in: network, matching: "Hauptbahnhof", kinds: [.stop])
guard let from = stops.first, let to = stops.dropFirst().first else { return }
for departure in try await client.departures(in: network, at: from, limit: 10) {
print(departure.scheduledTime, departure.line.name, departure.direction ?? "")
}
let found = try await client.trips(in: network, from: from, to: to, limit: 5)
// The same arguments again, with the reference to the trips after these.
let more = try await client.trips(in: network, from: from, to: to, limit: 5, page: found.later)
The documentation has this guide with a short program for each kind of request, which are also in examples.
Network.bundled(_:) gives a network that ships with the package by name. Registry.bundled() holds them all, for a list to choose from: network(id:) finds one by its ID as text, and covering(at:) lists the networks for a position. A Network can also be described in code or read from an entry in the format of transport-apis with Network(id:json:).
A stop or a place is a Location from a search, a departure or a trip, or a String with an ID; a place in trips can be a Coordinate too, or a CLLocationCoordinate2D where Core Location exists. A location that another network returned works as well: for a trip always if it has a coordinate, for departures where the asked network can name the stop, which EFA, TRIAS and OJP can for stops with a global ID. Each call also takes a query of the Rust library (LocationQuery, DeparturesQuery, TripsQuery) with the label query:.
Times are Date values. Location.timeZone is the time zone to show them in.
Location and Network are Identifiable. A Departure and a Trip have no identifier from the server; they are Hashable, so a list can use id: \.self.
What a query takes and what an answer holds is Codable: Location, Departure, Trip, the queries and the types inside them. An enum without values is stored as the name of its case, and a BundledNetwork as the ID of its network. An enum with values has the form that Swift writes for it, such as {"id": {"_0": "de:14612:28"}} for Place.id, and a Date the form that the encoder is set to. A Network is not Codable, because it can hold credentials and has a JSON form of its own; store its ID and find it again with Registry.bundled().network(id:).
The stored form follows the model, so it can change where the model does: with any minor version before 1.0, and with a major version after. Read stored values with try? and fetch them again when that fails. For what has to outlive an update, such as a favorite stop, store network.id and location.id.
Failures that the server or the query cause are thrown as PublicTransportError, such as .notFound or .rateLimited; its localizedDescription is a sentence in English. Failures of the HTTP exchange are thrown as URLError, and a cancelled task throws CancellationError. An answer above 16 MB is ClientError.responseTooLarge. The client does not follow redirects: a moved server is PublicTransportError.moved. It does not retry, limit its request rate or cache.
Some networks need more than their entry holds. Entur asks every client for its name in the header ET-Client-Name (company-application): add it to network.headers. An answer to trips from an OpenTripPlanner server can be empty at night and still have a later reference to follow.
Examples
The repository has these as programs to run, in examples.
Search for places by name
// Searches for places by name on the EFA server of VVO, the transport
// association of Dresden.
import Foundation
import PublicTransport
// Servers want to know who asks: name your application and a way to reach you.
let client = Client(userAgent: "publictransport-example (+https://github.com/kiliankoe/publictransport)")
let network = Network.bundled(.vvoEfa)
// Every kind of place. `kinds: [.stop]` asks for stops only.
let locations = try await client.locations(in: network, matching: "Dresden Zwinger")
// The best match comes first.
for location in locations.prefix(5) {
var position = ""
if let coordinate = location.coordinate {
position = String(format: " at %.4f, %.4f", coordinate.latitude, coordinate.longitude)
}
print("\(location.kind): \(location.name) (\(location.id))\(position)")
}
List the next departures at a stop
// Lists the next departures at a stop on the HAFAS server of VBB, the
// transport association of Berlin and Brandenburg.
import Foundation
import PublicTransport
// Servers want to know who asks: name your application and a way to reach you.
let client = Client(userAgent: "publictransport-example (+https://github.com/kiliankoe/publictransport)")
let network = Network.bundled(.vbbHafas)
let stops = try await client.locations(in: network, matching: "S+U Alexanderplatz", kinds: [.stop])
guard let stop = stops.first else { fatalError("found no stop") }
/// The time of day at the stop. Times are `Date` values, and a location
/// has the time zone to show them in.
func localTime(at stop: Location, _ time: Date) -> String {
time.formatted(Date.FormatStyle(time: .shortened, timeZone: stop.timeZone ?? .gmt))
}
print("Departures at \(stop.name):")
// From now on. `after:` asks for another time.
for departure in try await client.departures(in: network, at: stop, limit: 10) {
// Only departures with real-time data have a delay.
var delay = ""
if let realtime = departure.realtimeTime {
let minutes = Int(realtime.timeIntervalSince(departure.scheduledTime) / 60)
delay = minutes < 0 ? "\(minutes)" : "+\(minutes)"
}
print(
" \(localTime(at: departure.stop, departure.scheduledTime)) \(delay)"
+ " \(departure.line.name) \(departure.direction ?? "?")"
+ (departure.cancelled ? " (cancelled)" : ""))
}
Plan trips, and ask for later ones
// Plans trips between two stops on the OTP server of Entur, the journey
// planner for Norway, and asks for the trips after the first ones.
import Foundation
import PublicTransport
// Servers want to know who asks: name your application and a way to reach you.
let client = Client(userAgent: "publictransport-example (+https://github.com/kiliankoe/publictransport)")
var network = Network.bundled(.entur)
// Entur asks every client for its name, as `company-application`.
network.headers.append(Header(name: "ET-Client-Name", value: "publictransport-example"))
/// The expected time of day at the stop: the real-time one if there is
/// one. Times are `Date` values, and a location has the time zone to show
/// them in.
func localTime(_ end: LegEnd) -> String {
end.expectedTime.formatted(Date.FormatStyle(time: .shortened, timeZone: end.stop.timeZone ?? .gmt))
}
func printTrip(_ trip: Trip) {
guard let departure = trip.departure, let arrival = trip.arrival else { return }
print(" \(localTime(departure)) to \(localTime(arrival)), \(trip.transfers) change(s)")
for leg in trip.legs {
let how =
switch leg.kind {
case .transit(let line, let direction): "\(line.name) to \(direction ?? "?")"
case .walk: "walk"
default: "other"
}
print(
" \(localTime(leg.departure)) \(leg.departure.stop.name)"
+ " -> \(localTime(leg.arrival)) \(leg.arrival.stop.name): \(how)")
}
}
let origins = try await client.locations(in: network, matching: "Oslo S", kinds: [.stop])
let destinations = try await client.locations(in: network, matching: "Lillehammer stasjon", kinds: [.stop])
guard let origin = origins.first, let destination = destinations.first else { fatalError("found no stop") }
// Leaving now. `departingAt:` and `arrivingBy:` ask for another time.
// An end can also be a coordinate or the ID of a stop.
let found = try await client.trips(in: network, from: origin, to: destination, limit: 3)
print("Trips from \(origin.name) to \(destination.name):")
found.trips.forEach(printTrip)
// The same arguments again, with the reference to the trips after these.
if let later = found.later {
print("Later trips:")
let more = try await client.trips(in: network, from: origin, to: destination, limit: 3, page: later)
more.trips.forEach(printTrip)
}
Find the bundled networks for a position
// Lists the bundled networks that cover a position. This sends no request:
// the networks and their areas ship with the package.
import PublicTransport
let registry = Registry.bundled()
print("\(registry.networks().count) networks are bundled.")
let duesseldorf = Coordinate(latitude: 51.2198, longitude: 6.7943)
// The best coverage comes first: real-time data, then complete timetables,
// then any data.
print("At Düsseldorf Hauptbahnhof:")
for covering in registry.covering(at: duesseldorf) {
let network = covering.network
print(" \(covering.tier): \(network.name) (\(network.id), \(network.protocol))")
}
// A network by its ID, as an application would store it.
if let network = registry.network(id: "vrr-efa") {
print("vrr-efa is \(network.name) at \(network.endpoint)")
}