TripKit is a Swift-port of https://github.com/schildbach/public-transport-enabler with some additional enhancements. This library allows you to get data from public transport providers. Look into NetworkProvider.swift for an overview of the API.
TripKit is built using Swift 5.0 and requires iOS 10.0.
This library is currently used by the ÖPNV Navigator app in the iOS App Store.
let provider: NetworkProvider = KvvProvider() // Karlsruher Verkehrsverbund
let asyncTask = provider.suggestLocations(constraint: "Marktplatz", types: [.station], maxLocations: 10) { (result) in
switch result {
case .success(let locations):
for suggestedLocation in locations {
print(suggestedLocation.location.getUniqueShortName())
}
case .failure(let error):
print(error)
}
}
let asyncTask = provider.queryDepartures(stationId: "7000001", time: Date(), maxDepartures: 10, equivs: false) { (result) in
switch result {
case .success(let departures, _):
for departure in departures.flatMap { $0.departures } {
let label = departure.line.label ?? "?"
let destination = departure.destination?.getUniqueShortName() ?? "?"
let time = departure.getTime()
print("\(time): \(line) --> \(destination)")
}
case .invalidStation:
print("invalid station id")
case .failure(let error):
print(error)
}
}
let asyncTask = provider.queryTrips(from: Location(id: "7000001"), via: nil, to: Location(id: "7000002"), date: Date(), departure: true, products: nil, optimize: nil, walkSpeed: nil, accessibility: nil, options: nil) { (result) in
switch result {
case .success(let context, let from, let via, let to, let trips, let messages):
for trip in trips {
print(trip.id)
}
case .noTrips:
print("no trips could be found")
case .sessionExpired: // can only occur when querying for more trips
print("your session has expired")
case .ambiguous(let ambiguousFrom, let ambiguousVia, let ambiguousTo):
print("from, via or to location could not be identified (probably because no stop id has been provided)")
case .invalidDate:
print("invalid date")
case .tooClose:
print("from and to location are too close nearby")
case .unknownFrom:
print("unknown from location")
case .unknownVia:
print("unknown via location")
case .unknownTo:
print("unknown to location")
case .failure(let error):
print(error)
}
}
// journeyContext can be obtained from a PublicLeg instance.
let asyncTask = provider.queryJourneyDetail(context: journeyContext) { (result) in
switch result {
case .success(let trip, let leg):
print(leg.intermediateStops)
case .invalidId:
print("invalid context")
case .failure(let error):
print(error)
}
}
More api methods can be found in NetworkProvider.swift.
For some providers a secret like an API key is required to use their API. You need to request the secrets directly from the provider or use the same ones that are used by the official apps. For Navitia based providers, you can request a secret here.
For unit testing, you need to specify all required secrets in a secrets.json file. A template can be found here.